Measure-Command

Measure-Command: Measure Execution Time in PowerShell

Welcome back to Wahmans Powershell blog! Today we’re exploring a particularly useful cmdlet when it comes to performance tuning, benchmarking, or just satisfying your curiosity: Measure-Command. According to Microsoft, this cmdlet “Measures the time it takes to run script blocks and cmdlets.” And that’s exactly what it does—delivering back a TimeSpan object that tells you how long a piece of PowerShell code took to run.

So, whether you’re wondering which of two functions runs faster, trying to profile a script, or just want to get nerdy with your automation, Measure-Command is here to help.

Syntax

Measure-Command -Expression { <command or script block> }

Let’s walk through four examples ranging from beginner-friendly basics to slightly more involved real-world use cases.

Example 1: Measuring a simple command

This beginner example shows how long it takes to get a list of all running processes.

Measure-Command { Get-Process }

Example 2: Comparing performance between two alternatives

Want to see which command is faster? Let’s compare piping with and without Where-Object against Get-Process -Name.

# Using Get-Process with filter
$method1 = Measure-Command { Get-Process -Name powershell }

# Using Where-Object to filter
$method2 = Measure-Command { Get-Process | Where-Object { $_.Name -eq "powershell" } }

"Method 1 duration: $($method1.TotalMilliseconds) ms"
"Method 2 duration: $($method2.TotalMilliseconds) ms"

Example 3: Benchmarking a function call

Let’s measure the execution of a custom function that performs some data operations.

function Get-SortedRandomNumbers {
    $data = 1..10000 | ForEach-Object { Get-Random -Minimum 1 -Maximum 10000 }
    $data | Sort-Object
}

Measure-Command { Get-SortedRandomNumbers }

Example 4: Advanced – Logging performance of script steps

When building more complex scripts, it’s useful to measure performance of individual sections.

$stepDurations = @{}

$stepDurations["Fetch Data"] = Measure-Command {
    Start-Sleep -Milliseconds 500 # Simulate data fetching
}

$stepDurations["Process Data"] = Measure-Command {
    1..10000 | ForEach-Object { $_ * 2 } | Out-Null
}

$stepDurations["Save Results"] = Measure-Command {
    Start-Sleep -Milliseconds 250 # Simulate saving to disk
}

foreach ($step in $stepDurations.Keys) {
    "$step took $($stepDurations[$step].TotalMilliseconds) ms"
}

Final Thoughts

Measure-Command is an under-rated gem in the PowerShell toolbox. It’s quick, easy to use, and highly effective for profiling performance in scripts, cmdlets, and even entire workflows.

Don’t forget that the cmdlet measures the execution time of everything within the script block—including potential delays like disk IO or network calls—so it’s great for realistic timing in many contexts.

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 *