C# ASP.NET SQL SERVER

Powershell Get-ChildItem - FileSystemInfo or Array

I've just discovered something interesting in my ventures into Powershell. If a directory has a single file in it then the Get-ChildItem in that directory will return a System.IO.FileSystemInfo object but if there are 2 or more files then it will return a System.Array object.

I'm running a script and in the script I'm getting a count of the number of files in each of several directories. So what I've found that I have to do is to check the value of the "count" member return and if it's null then I assume that the object is a System.IO.FileSystemInfo object and call the Directoy.GetFiles().count member to get the number (1) of files in there.

This is what that little snippet in my Powershell script looks like now:

        $fileCollection = Get-ChildItem $s
        if($fileCollection -eq $null)
        {
            $fileCount = 0
        }
        else
        {
            $fileCount = $fileCollection.count
        }
       
        if($fileCount -eq $null)
        {
            # This happens if a directory has 1 file in it. Instead of receiving an Array object back
            # from the Get-ChildItem call we receive a System.IO.FileSystemInfo object and we need
            # to call the Directoy.GetFiles().count on that to get the right value.
            $fileCount = $fileCollection.Directory.GetFiles().count
        }
        $totalFileCount += $fileCount
 

» Similar Posts

  1. Powershell Ripped Media Renaming Script
  2. Unable to cast object of type 'System.Int32' to type 'System.String'
  3. Download List of Files from Web with Powershell Script

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://guyellisrocks.com/trackback.ashx?id=22

» Comments

  1. Sebastian Rogers avatar

    Or you can coerce the return to be an array with the @ operator, e.g.

    @(get-childitem c:\scripts).Count

    Simple and effective

    Sebastian Rogers — June 19, 2008 11:18 AM
  2. Guy Ellis avatar

    Thanks Sebastian! I've subsequently discovered some more tricks in Powershell and your suggestion is one of them that makes it much easier and my original solution posted above is not looking that good anymore. :)

    Guy Ellis — June 19, 2008 3:11 PM
  3. David Catto avatar

    Sebastian,

    Many thanks for that. I had this problem and your '@' worked a treat. pitty microsoft did not have that there. They tend to assume that people have a good understanding before they go to their sites.

    thanks again.

    David

    David Catto — July 23, 2008 2:13 PM

» Leave a Comment