How to Use Measure-Object in PowerShell: Syntax and Examples
Use the
Measure-Object cmdlet in PowerShell to calculate the count, sum, average, minimum, and maximum of object properties or to count objects. It works by piping objects to it and specifying properties or calculation options with parameters like -Property and -Sum.Syntax
The basic syntax of Measure-Object is:
Measure-Object [-Property] <string[]> [-Sum] [-Average] [-Minimum] [-Maximum] [-Line] [-Word] [-Character] [-InputObject] <psobject>Measure-Objectcan be used with or without properties to count objects or calculate statistics.-Propertyspecifies which property to measure.-Sum,-Average,-Minimum,-Maximumspecify the calculation type.-Line,-Word,-Characterare used for text measurements.
powershell
Get-Process | Measure-Object -Property CPU -Sum -Average -Minimum -Maximum
Example
This example shows how to get the count, sum, average, minimum, and maximum of the CPU time used by running processes.
powershell
Get-Process | Measure-Object -Property CPU -Sum -Average -Minimum -Maximum
Output
Count : 123
Average : 12.345678
Sum : 1519.135802
Maximum : 250.123456
Minimum : 0.001234
Property : CPU
Common Pitfalls
Common mistakes when using Measure-Object include:
- Not specifying
-Propertywhen you want to calculate sums or averages, which causes it to just count objects. - Trying to sum or average non-numeric properties, which results in errors or no meaningful output.
- Using
Measure-Objecton empty input, which returns zero counts but no sums or averages.
Always ensure the property you measure is numeric for calculations.
powershell
Get-Process | Measure-Object -Sum # Correct usage: Get-Process | Measure-Object -Property CPU -Sum
Quick Reference
| Parameter | Description |
|---|---|
| -Property | Specifies the property to measure |
| -Sum | Calculates the sum of the property values |
| -Average | Calculates the average of the property values |
| -Minimum | Finds the minimum value of the property |
| -Maximum | Finds the maximum value of the property |
| -Line | Counts lines in text input |
| -Word | Counts words in text input |
| -Character | Counts characters in text input |
Key Takeaways
Use Measure-Object to count or calculate statistics on object properties in PowerShell.
Always specify -Property for numeric calculations like sum or average.
Measure-Object can also count lines, words, or characters in text input.
Avoid measuring non-numeric properties for sum or average to prevent errors.
Pipe objects into Measure-Object to analyze collections easily.