How to Measure Script Runtime in PowerShell

This is a short Blogpost, but very useful. When writing scripts, it is often important to understand how long a script or command takes to execute. Measuring script runtime can help identify slow operations, analyze performance, and improve automation processes.

In many environments scripts run regularly, for example in scheduled tasks, background jobs, or Azure Automation runbooks. If the runtime of a script suddenly increases, it may indicate inefficient logic, external service delays, or other performance issues.

Keeping an eye on script runtime helps maintain automations and makes troubleshooting much easier. PowerShell provides several simple methods to measure execution time, which will be demonstrated in the following examples.

Using Measure-Command

The easiest way to measure runtime in PowerShell is the Measure-Command cmdlet. This cmdlet executes a block of code and returns the time required to complete it.

PowerShell
$result = Measure-Command {
Get-Process
}
$result

The returned object contains several properties describing the runtime of the command.

Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 166
Ticks : 1663845
TotalDays : 1,92574652777778E-06
TotalHours : 4,62179166666667E-05
TotalMinutes : 0,002773075
TotalSeconds : 0,1663845
TotalMilliseconds : 166,3845

This method is very useful when quickly testing how long a command or small script block takes to run.

Measuring Runtime with Get-Date

Another common approach is capturing the start and end time of a script. This method is often used inside automation scripts when runtime information should be logged.

PowerShell
$start = Get-Date
# Script logic
Start-Sleep -Seconds 2
$end = Get-Date
$runtime = $end - $start
$runtime

The result is a TimeSpan object representing the duration of the script execution.

Days : 0
Hours : 0
Minutes : 0
Seconds : 2
Milliseconds : 3
Ticks : 20030997
TotalDays : 2,31840243055556E-05
TotalHours : 0,000556416583333333
TotalMinutes : 0,033384995
TotalSeconds : 2,0030997
TotalMilliseconds : 2003,0997

Summary

Measuring script runtime is a simple but powerful technique when working with PowerShell automation. Understanding how long scripts take to run can help detect slow operations, identify bottlenecks, and improve overall automation performance.

PowerShell provides multiple easy ways to measure runtime. The Measure-Command cmdlet is ideal for quick testing, while using Get-Date provides more flexibility when logging execution time inside scripts.

Leave a comment