PowerShell for Windows Admins

Aug 20 2014   10:19AM GMT

Count property

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: