Count property

Its frequently said that PowerShell is so big that no one can know everything about it.  I proved that today when I “discovered” a change in PowerShell of which I wasn’t aware.

 

If you create an array:

£> $a = 1,2,3

You can then get the number of members of that array i.e. its length

 

£> $a.count
3

 

£> $a[0]
1

 

In PowerShell 1.0 and 2.0 if you tried that on a variable that only held a single value you would get an error when you tried to access the first value:

£> $b = 1


£> $b.count

The count property returns nothing

 

£> $b[0]
Unable to index into an object of type System.Int32.
At line:1 char:4
+ $b[ <<<< 0]
    + CategoryInfo          : InvalidOperation: (0:Int32) [], RuntimeException
    + FullyQualifiedErrorId : CannotIndex

 

This changed in PowerShell 3.0 and later

£> $b = 1
£> $b.count
1


£> $b[0]
1

 

You can even try other indices
£> $b[1]
£>

 

And just get nothing back rather than an error.

 

This is really useful as you can now safely test on the Count property and if the value is greater than 1 to determine if its a collection.  Alternatively always treat it as a collection and iterate over the number of elements.  I can see this simplifying things for me in quite a few situations

One Response to Count property

  • Hi Richard,

    It’s worth noting that this is only true if you have “Set-Strictmode -Off” (the default).

    In a script with “Set-Strictmode -Version Latest” or “Set-Strictmode -Version 3″ (or if you have that in your profile as I do) then $b.count and $b[1] give errors (although $b[0] still works).

    Cheers,
    Chris

Leave a Reply