How to count objects in PowerShell?

ulidtko picture ulidtko · Jul 17, 2012 · Viewed 424.1k times · Source

As I'm reading in the PowerShell user guide, one of the core PowerShell concepts is that commands accept and return objects instead of text. So for example, running get-alias returns me a number of System.Management.Automation.AliasInfo objects:

PS Z:\> get-alias

CommandType     Name                                             Definition
-----------     ----                                             ----------
Alias           %                                                ForEach-Object
Alias           ?                                                Where-Object
Alias           ac                                               Add-Content
Alias           asnp                                             Add-PSSnapIn
Alias           cat                                              Get-Content
Alias           cd                                               Set-Location
Alias           chdir                                            Set-Location
...

Now, how do I get the count of these objects?

Answer

jumbo picture jumbo · Jul 17, 2012

This will get you count:

get-alias | measure

You can work with the result as with object:

$m = get-alias | measure
$m.Count

And if you would like to have aliases in some variable also, you can use Tee-Object:

$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases

Some more info on Measure-Object cmdlet is on Technet.

Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)