Measuring how long a PowerShell command takes to run gives you exact control over performance, debugging bottlenecks, and optimizing automation tasks. To time a command directly, use the built-in Measure-Command function—it returns execution time in seconds with nanosecond precision. For more detailed timing (including wait time), combine it with Start-Time or Stop-Process where needed.
What You'll Need
- PowerShell (version 3.0+ recommended, but works on all versions)
- A script or command you want to time (e.g.,
Get-ChildItem, a long-running process, or a custom script) - Optional: A text editor or script file to store commands (e.g.,
.ps1files)
Step-by-Step
- Open PowerShell as Administrator or with sufficient permissions if your command requires elevated rights. Open a new terminal window or clear the existing one before timing to avoid cached results interfering with timing accuracy.
-
Use the simplest timing method:
Measure-Commandwith your command. For example:Measure-Command { Get-ChildItem -Path "C:\Temp" }This returns execution time in seconds as a decimal (e.g., 0.2345 seconds). To see it in a more readable format, pipe toFormat-List:Measure-Command { Get-ChildItem -Path "C:\Temp" } | Format-ListResult:TotalSeconds = 0.2356789 -
For commands that block or wait, use nested
Measure-Commandblocks:Measure-Command { Start-Sleep -Seconds 5; Get-Service }This measures total time including waiting. -
To log execution time to a file, redirect output:
Measure-Command { Get-Process } | Out-File "ExecutionTime.log" -
For scripts, open your .ps1 file in an editor, insert timing commands at strategic points, and run them in PowerShell:
Start-Time { # Script block here }Stop-Time
Common Mistakes
-
Timing only the last command in a script instead of the entire block. Use nested
Measure-Commandblocks to capture full execution, including waits. Example:Measure-Command { # Long-running operations Start-Sleep -Seconds 3 Write-Output "Completed" } -
Ignoring script scope. If your command references external files or global variables, ensure those aren’t cached in the current session. Restart PowerShell or run with
-NoExitto avoid session interferences. -
Using default time resolution. On Windows,
Measure-Commandreports time in milliseconds by default. To force seconds, add-Seconds:Measure-Command -Seconds { Get-Service }
Tips
-
For precise timing of external processes (e.g., batch scripts), use
Start-Processwith timing:Start-Process cmd.exe /c "timeout /t 10" | Measure-Command -
Use
Invoke-Expressionto run commands safely from strings:Measure-Command (Invoke-Expression "Get-Process firefox") -
For complex workflows, break timing into stages:
Measure-Command { $a = Get-Date; # Task 1; $b = Get-Date; # Task 2; $c = $b - $a } -
Use
-PassThruto capture output while timing:Measure-Command -PassThru { Get-Process } | Select-Object TotalSeconds -
Benchmark multiple runs for consistency:
Measure-Command { Get-ChildItem } | Select-Object @{Name="Avg";Expression={($_.TotalSeconds/10)} }
Troubleshooting
-
If timing returns 0 seconds:
- Your command might be synchronous (e.g.,
Write-Output) or already cached. Use-NoMeasureto test:Measure-Command -NoMeasure { Get-Service } - Check for typos or missing quotes. Test a simple command like
Get-Versionfirst. - Restart PowerShell or run the command in a new session. Old executions may linger in memory.
- Your command might be synchronous (e.g.,
-
For commands that fail with timing:
Measure-Command { Get-Service Network -ErrorAction SilentlyContinue }Capture results viaOut-Hostto avoid errors silencing output. -
Timing hangs or runs indefinitely:
- Add a
throwat the end of your block:Measure-Command { # Long task; throw }This forces completion and reveals issues. - Check for silent errors with
-ErrorAction Stop:Measure-Command -ErrorAction Stop { Get-Process * }
- Add a
-
If PowerShell refuses to measure:
- Ensure the command isn’t blocked by another process (e.g., a locked file). Use
Try { ... } Finally { Write-Warning "Failed" }to debug. - Test in a clean environment. Run
Get-Command Measure-Commandto confirm the cmdlet exists.
- Ensure the command isn’t blocked by another process (e.g., a locked file). Use
Frequently Asked Questions
How do I time a schedule task in PowerShell?
Use Start-Time and Stop-Time in a script that triggers the task. Example:
Start-Time { & "C:\Program Files\WindowsPowerShell\Modules\Schedule\RunTask.ps1" -TaskName "MyTask" -RunAsAdmin }
$total = Stop-Time
Note: Requires the Schedule module. Install with Install-Module -Name Schedule.
Can I time PowerShell commands in a script file?
Yes, use Measure-Command directly in your script:
Measure-Command {
$start = Get-Date
# Your script block here
$end = Get-Date
$elapsed = $end - $start
Write-Output "Duration: $elapsed"
}
Why does timing show 0 seconds for some commands?
Commands like Write-Output or Get-ChildItem may complete instantly due to caching. Force measurement by adding a deliberate delay:
Measure-Command { Start-Sleep -Milliseconds 1; Write-Output "Test" }
How do I time a multi-threaded PowerShell command?
Use Measure-Command -PassThru and filter threads:
Measure-Command { Start-ThreadJob { Get-Process } } | ForEach-Object { $_.Threads.Count }
Is there a way to time a PowerShell command in a GUI app?
No, GUI apps (like Get-Service in the GUI) don’t expose timing directly. Use Invoke-Command to run PowerShell commands from GUIs:
Invoke-Command { Measure-Command { Get-Service } }
How do I compare execution time between two commands?
Run both commands in separate Measure-Command blocks and use Compare:
Measure-Command { Get-ChildItem }
Measure-Command { Get-Process }
Compare-Object @(0.23) @(0.15)