Measure-Object

PowerShell Cmdlet Spotlight: Measure-Object

Welcome back to Wahmans Powershell Blog! Today, we’re diving into a foundational but powerful cmdlet that every PowerShell user should have in their toolbox: Measure-Object. According to Microsoft, this cmdlet “calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text.”

That simple summary hides a lot of utility! Whether you’re counting lines in a file, finding the average of a list of numbers, or analyzing file content, Measure-Object is a fantastic go-to cmdlet. Let’s cover four practical examples, ranging from beginner to advanced usage.

🔰 Example 1: Count Items in an Array (Beginner)

$array = 1, 2, 3, 4, 5
$array | Measure-Object

This basic example shows how many items are in the array and gives you the minimum, maximum, sum, and average.

📝 Example 2: Count Lines, Words, and Characters in a Text File (Intermediate)

Get-Content -Path ".\example.txt" | Measure-Object -Line -Word -Character

This is incredibly useful for analyzing content in scripts, logs, or documentation. The result provides a summary of the number of lines, words, and characters in the file.

📊 Example 3: Statistical Analysis on File Sizes (Intermediate+)

Get-ChildItem -Path "C:\Logs" -Recurse | 
    Where-Object { -not $_.PSIsContainer } | 
    Measure-Object -Property Length -Sum -Average -Maximum -Minimum

Want to know how much disk space a directory of files is using, or find out the average file size? This example shows how to get size statistics for all files under the Logs directory.

🚀 Example 4: Measure Values from Custom Objects (Advanced)

$data = @(
    [PSCustomObject]@{Name='Server01'; Usage=70},
    [PSCustomObject]@{Name='Server02'; Usage=85},
    [PSCustomObject]@{Name='Server03'; Usage=65}
)

$data | Measure-Object -Property Usage -Minimum -Maximum -Average

In more advanced scenarios, you can use Measure-Object on properties from custom objects. This is highly useful in reports and dashboards where you are handling usage, metrics, or performance data.

And that’s just scratching the surface! Keep exploring new ways to use Measure-Object in your automation and analysis scripts.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *