DCSIMG
Counting objects in PowerShell 3.0 - Shay Levy

Shay Levy

If you repeat it, PowerShell it!

News


btn_donate_LG

View Shay Levy's profile on LinkedIn Follow Shay Levy at Twitter Shay Levy's Facebook profile Subscribe to my FriendFeed


site statistics




Counting objects in PowerShell 3.0

Consider the following command, how many objects are in $dir?

PS> $dir = Get-ChildItem


The most common way to find it is to check the Count property:

PS> $dir.Count


But… the Count property is available only if Get-Something returns more than one object (array/collection), If the result has one object only (scalar) the Count property returns nothing, not even zero. If the result contains more than one object, the objects are accumulated in an Array (collection), and Arrays have a Count property so we get the number of objects.

Now back to the question above, how can we safely determine object count? The most common solution was to use the @(…) array construction to force the result to an array:

PS> @($dir).Count


Now Count will return 0 or another positive number. Although we could get object count this way, it was very irritating and tedious to always make sure to convert the output!

In PowerShell 3.0 the saga ends! We are no longer required to convert the result. The magicians at Microsoft had spread some of their magic powder and now the Count property is available on single objects as well!

# get the process that is hosting the current Windows PowerShell session 
PS> $ps = Get-Process -Id $PID 
PS> $ps.Count
1


If you try to use tab completion on a single object, Count will not be one of the options and it is also not visible to the Get-Member cmdlet, you need to explicitly write it in order to get the value.

One more thing to notice is when the command didn’t return any objects($null result). Unlike other languages, $null in PowerShell “has” a Count property, and it makes sense. If you base you script on the Count property you may get 0 or 1 or more objects. In the case of the former, $null.count gives back 0.

Enjoy!

Comments

Manoj Nair said:

Wow, that is impressive. Thanks PowerShay :)

# March 24, 2012 1:36 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: