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