0
0
PowershellHow-ToBeginner · 3 min read

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-Object can be used with or without properties to count objects or calculate statistics.
  • -Property specifies which property to measure.
  • -Sum, -Average, -Minimum, -Maximum specify the calculation type.
  • -Line, -Word, -Character are 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 -Property when 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-Object on 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

ParameterDescription
-PropertySpecifies the property to measure
-SumCalculates the sum of the property values
-AverageCalculates the average of the property values
-MinimumFinds the minimum value of the property
-MaximumFinds the maximum value of the property
-LineCounts lines in text input
-WordCounts words in text input
-CharacterCounts 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.