0

I have a portion of a powershell script that checks locations and verifies the count of files, then runs checks based on the count. The powershell script is ran on multiple machines, one of which is running powershell 2.0.

I'm using something like:

$folder = Get-Item "Parent Folder"
$files  = (Get-ChildItem $folder.Fullname)

When I check $files.Count it will be accurate in versions of powershell greater than 2.0. In Powershell 2.0, files.Count will not return anything if $files only contains 1 file. If there is more than 1 file, then it returns the correct number count (non-null).

I'm assuming this has to do with $files not being an array if Get-ChildItem only returns one value.

I know that checking the powershell version and modifying the script per version would resolve this issue, but I'd prefer to avoid it.

Is there some other way to check the count uniformly across multiple versions of powershell?

Speerian
  • 1,138
  • 1
  • 12
  • 29

1 Answers1

4

That's a known gotcha, you have to cast return value to array for PS 2.0. It was fixed in PS 3.0:

You can now use Count or Length on any object, even if it didn’t have the property. If the object didn’t have a Count or Length property, it will will return 1 (or 0 for $null). Objects that have Count or Length properties will continue to work as they always have.

Example:

$files = @(Get-ChildItem $folder.Fullname)

or

[array]$files = Get-ChildItem $folder.Fullname

References:

Community
  • 1
  • 1
beatcracker
  • 6,714
  • 1
  • 18
  • 41
  • 2
    IMHO, does not use cast to `[array]`. It does not return empty array in case of empty pipeline. And if pipeline return single element and that single element is collection, then cast to `[array]` will copy elements of collection to array instead of wrapping collection in single element array, as `@()` does. – user4003407 Oct 28 '15 at 17:59
  • @PetSerAl Agreed, thanks for clarifying. `[array]` behavior sometimes is more preferable, because in case of empty return value it will contain `$null` which can be easily compared using comparison operators. It's not so straightforward with empty arrays, because when being used against an array, [comparison operators do not return a boolean value ($true or $false). They return all the members of the array that meet the condition.](http://stackoverflow.com/a/29614241/4424236) – beatcracker Oct 28 '15 at 19:36
  • In case of empty array, you can just compare `$array.Count -eq 0` or `-not $array.Count`. – user4003407 Oct 28 '15 at 19:40