Measure Object - PowerShell


Overview

Measure-Object calculates and displays statistical information about the properties of objects in a collection. It is widely used in PowerShell to analyze data and perform statistical calculations on the fly.

Syntax

Measure-Object [-InputObject] <object> [-Property] <string[]> [-Sum] [-Average] [-Maximum] [-Minimum] [-Count] [-StandardDeviation] [-Variance] [-Filter <string>] [-Exclude <string[]>] [-ErrorAction <string>] [-ErrorVariable <string>] [-Wait] [-AsJob] [-OutFile <string>] [-OutVariable <string>]

Options/Flags

  • -InputObject : Specifies the collection of objects to measure.
  • -Property <string[]>: Indicates the property or properties to measure.
  • -Sum: Calculates the sum of the specified property values.
  • -Average: Calculates the average of the specified property values.
  • -Maximum: Computes the maximum value of the specified property.
  • -Minimum: Computes the minimum value of the specified property.
  • -Count: Counts the number of objects in the collection.
  • -StandardDeviation: Calculates the standard deviation of the specified property values.
  • -Variance: Computes the variance of the specified property values.
  • -Filter : Filters the input objects based on a specified condition.
  • -Exclude <string[]>: Excludes specified properties from the measurements.
  • -ErrorAction : Controls how the command handles errors.
  • -ErrorVariable : Stores any errors encountered during execution.
  • -Wait: Suspends the execution of the command until the job completes.
  • -AsJob: Runs the command as a background job.
  • -OutFile : Saves the results to a text file.
  • -OutVariable : Stores the results in a specified variable.

Examples

Example 1: Calculate Average Memory Usage of Processes

Get-Process | Measure-Object -Property WorkingSet -Average -OutVariable AvgMemory
$AvgMemory

Example 2: Display Statistical Information for File Sizes

Get-ChildItem -Path C:\Directory | Measure-Object -Property Length -Sum -Average -Maximum -Minimum

Example 3: Filter Objects Before Measurement

Get-Service | Where {$_.Status -eq "Running"} | Measure-Object -Property Status -Count -Filter 'Status -eq "Running"'

Common Issues

  • Inconsistent Property Names: Ensure that the property name specified in the -Property parameter matches the actual property name in the objects.
  • Invalid Input: Verify that the input objects have the required properties for measurement.
  • Excessive Output: When measuring multiple properties, the output can become large. Consider using -OutVariable to store the results in a variable.

Integration

Combine with Other Commands:

Get-Process | Sort-Object -Descending WorkingSet | Measure-Object -Property WorkingSet -Top 10

Create Scripts:

$script = @"
Get-Service | Measure-Object -Property Status -Count -OutFile C:\SvcStats.txt
"@
Invoke-Expression $script