Thursday, May 22, 2008

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
 

9 comments:

  1. Or you can coerce the return to be an array with the @ operator, e.g.
    @(get-childitem c:\scripts).Count
    Simple and effective

    ReplyDelete
  2. 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. :)

    ReplyDelete
  3. 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

    ReplyDelete
  4. the @ trick is great!!!

    ReplyDelete
  5. Thank you! That helped a lot. :)

    ReplyDelete
  6. The @ trick worked great!! Thanks!

    ReplyDelete
  7. Great tip, resolved my problem and saved me time!

    ReplyDelete
  8. Thank you ! for the @ trick!!!

    ReplyDelete
  9. Thanks for the Post.
    Although the post is old i wanted to add this incase someone stumbes upon it.
    You can also force the array by starting your variable with [array]$MyVar
    Then count will return 1

    ReplyDelete