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:
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:
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
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.