Counting members

If you have a collection of objects

$proc = get-process

you can get the number of members using the Length property

PS>  $proc.Length
71

$proc is of type System.Array

PS>  $proc.GetType()

IsPublic IsSerial Name                                     BaseType
——– ——– —-                                     ——–
True     True     Object[]                                 System.Array

MSDN documenattion is at https://msdn.microsoft.com/en-us/library/system.array(v=vs.110).aspx

PowerShell also adds a Count property that is an alias of Length

if you are after the number of members in a collection via the pipeline you need to use the Measure-Object cmdlet

PS>  $proc | Measure-Object

Count    : 71
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

or measure directly

PS>  Get-Process | Measure-Object

Count    : 71
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Notice that Measure-Object can also be used to discover other statistics – the Average, Sum, Maximum and Minimum. These only work for numeric properties.

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

One Response to Counting members

  1. Jaap Brasser says:

    I think an interesting note on this subject is that there is different behavior if you are on versions of PowerShell older than 3.0. The following example assume only a single instance of notepad is running on the system:

    (Get-Process notepad).count
    3.0 returns 1
    2.0 returns nothing, property does not exist

    Something to be aware of when writing code that should be compatible with all versions of PowerShell.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s