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.
$result = Measure-Command { Get-Process}$result
The returned object contains several properties describing the runtime of the command.
Days : 0Hours : 0Minutes : 0Seconds : 0Milliseconds : 166Ticks : 1663845TotalDays : 1,92574652777778E-06TotalHours : 4,62179166666667E-05TotalMinutes : 0,002773075TotalSeconds : 0,1663845TotalMilliseconds : 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.
$start = Get-Date# Script logicStart-Sleep -Seconds 2$end = Get-Date$runtime = $end - $start$runtime
The result is a TimeSpan object representing the duration of the script execution.
Days : 0Hours : 0Minutes : 0Seconds : 2Milliseconds : 3Ticks : 20030997TotalDays : 2,31840243055556E-05TotalHours : 0,000556416583333333TotalMinutes : 0,033384995TotalSeconds : 2,0030997TotalMilliseconds : 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.