When writing PowerShell scripts, you’ll sometimes want to know how long a specific task takes. For example: how fast does a file load, how long does an API call take, or how efficient is a particular loop?

PowerShell has a built-in cmdlet for this: Measure-Command.

What does Measure-Command do?

Measure-Command runs a block of code and returns how long it took to execute. The result is a TimeSpan object with details like seconds, milliseconds, and more.

Example: Measuring the time of a file scan

$duration = Measure-Command {
    Get-ChildItem -Path "C:\Windows\System32" -Recurse | Where-Object { $_.Length -gt 1MB }
}

Write-Host "Scan duration: $($duration.TotalSeconds) seconds"

 Use Case: Comparing Two Methods

$method1 = Measure-Command {
    1..10000 | ForEach-Object { $_ * 2 }
}

$method2 = Measure-Command {
    foreach ($i in 1..10000) { $i * 2 }
}

Write-Host "ForEach-Object: $($method1.TotalMilliseconds) ms"
Write-Host "foreach-loop: $($method2.TotalMilliseconds) ms"

This is a great way to compare performance between different approaches. In this example, we test how long it takes to multiply numbers using ForEach-Object versus a traditional foreach loop.

Disclaimer

Measure-Command is great for quick benchmarks, but it’s not suitable for micro-benchmarking (like using Stopwatch in C#). Especially with smaller, less intensive code blocks, you’ll see a lot of variation in timing results.

That’s why it’s a good idea to run your test multiple times and calculate the average. This makes your measurement much more reliable /and that advice applies not just to small code blocks, but to any performance test.

Example: Calculating Average Execution Time

$times = @()
for ($i = 0; $i -lt 5; $i++) {
    $times += (Measure-Command { Get-Random -Minimum 1 -Maximum 1000000 }).TotalMilliseconds
}
$average = ($times | Measure-Object -Average).Average
Write-Host "Average: $([math]::Round($average, 2)) ms"

This snippet runs the same command five times and calculates the average execution time in milliseconds.

Conclusion

Measure-Command is a simple yet powerful tool to gain insight into the performance of your PowerShell code. Whether you’re optimizing scripts or just curious. To measure is to know.

Leave a Reply

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