Measure-Object: Quantifying data within PowerShell

Posted by:

|

On:

|

With as useful as Measure-Object is, I’m surprised you don’t see more about this cmdlet online. While you can just type math into PowerShell and it will compute, cmdlets allow for the calculation of sums, averages, standard deviations, and more.

Quantifying Numbers with Measure-Object

This cmdlet can compute various statistical measures for numerical data in a collection. For example, you can use it to calculate the sum, average, minimum, and maximum values of a set of numbers.

PowerShell
$numbers = 1, 2, 3, 4, 5
$numbers | Measure-Object -Sum -Average -Minimum -Maximum

This can also be used with script blocks. This can be useful for conditional logic such as raising an exit code if something didn’t evaluate right.

PowerShell
$data = 1..10 | ForEach-Object { $_ * 2 }
$data | Measure-Object -Sum

Lastly, you can measure all stats available on a collection of numbers.

PowerShell
1..5 | Measure-Object -AllStats

Quantifying Strings

We can also quantify strings. For example, you can use it to count characters or words in a text file or string. This is helpful for text processing tasks.

PowerShell
$text = "This is a sample text."
$text | Measure-Object -Character -Word

If you’re only interested in unique words, this can be filtered to only count unique items in the collection.

PowerShell
$fruits = "apple", "banana", "apple", "orange", "banana"
$fruits | Measure-Object -Unique

Text files can also be read and used as input. This could be applied to logs, output files, or other documents.

PowerShell
"One", "Two", "Three", "Four" | Set-Content -Path C:\Temp\tmp.txt
Get-Content C:\Temp\tmp.txt | Measure-Object -Character -Line -Word

Using Objects

Lastly, properties of objects such as running processes or CSV headers can be parsed into this cmdlet.

PowerShell
Get-Process | Measure-Object -property ProcessName

Imagine you had a CSV file that had the header “yearsExp” and you wanted to see how much experience on average the applicants have.

PowerShell
Import-Csv d:\scripts\NewApplicants.csv | Measure-Object -Property yearsExp -Minimum -Maximum -Average

A simple use-case could be determining the number of files and folders within a directory, which can be beneficial for tasks such as monitoring folder size and assessing file counts. This will also work if you add parameters to Get-ChildItem, such as -Filter, -Recurse or -Directory.

PowerShell
Get-ChildItem -Recurse | Measure-Object
Get-ChildItem -Directory | Measure-Object

This is a useful tool, but most people can get by doing math in the terminal or by using methods such as .count on objects. I am not particularly gifted or afflicted regarding math but am always happy to offload brainpower to a computer!