PowerShell Measure and Count
Measure-Object is a cmdlet that summarizes numbers flowing through the pipeline. It can count them, add them up, or find their average, largest, and smallest values.
Add numbers up
Pipe a range into Measure-Object -Sum. Then print only the .Sum property.
(1..5 | Measure-Object -Sum).SumCount the items that pass a filter
Filter the range first, then measure it. The .Count property tells how many items survived.
(1..10 | Where-Object { $_ -gt 7 } | Measure-Object).CountFind the average and the extremes
One Measure-Object call can compute several summaries at once. Print each property on its own line.
$result = 1..4 | Measure-Object -Average -Maximum -Minimum
$result.Average
$result.Maximum
$result.MinimumExample
$result = 1..20 | Where-Object { $_ % 2 -eq 0 } | Measure-Object -Sum -Average
$result.Sum
$result.AverageKey points
- Summary: Measure-Object turns a stream of numbers into one summary.
- Sum: The .Sum property holds the total of the numbers.
- Count: The .Count property holds how many numbers there were.
- Average: The .Average property holds the mean of the numbers.
- Extremes: The .Maximum property holds the largest number, and .Minimum holds the smallest.
In this example, the even numbers from 1 to 20 are filtered out first. Measure-Object then adds them up and averages them, and the example prints the .Sum and .Average properties.
Note
Never print the Measure-Object result itself. Print one of its properties, like .Sum or .Count.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does (1..4 | Measure-Object -Sum).Sum print?