Counting objects in PowerShell 3.0

March 19, 2012

one comment

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

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.


Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


one comment

  1. Manoj NairMarch 24, 2012 ב 13:36

    Wow, that is impressive. Thanks PowerShay 🙂