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
Or you can coerce the return to be an array with the @ operator, e.g.
ReplyDelete@(get-childitem c:\scripts).Count
Simple and effective
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. :)
ReplyDeleteSebastian,
ReplyDeleteMany 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
the @ trick is great!!!
ReplyDeleteThank you! That helped a lot. :)
ReplyDeleteThe @ trick worked great!! Thanks!
ReplyDeleteGreat tip, resolved my problem and saved me time!
ReplyDeleteThank you ! for the @ trick!!!
ReplyDeleteThanks for the Post.
ReplyDeleteAlthough 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