- Courses
- đź’»Programming Languages
- 🪟PowerShell
- PowerShell Scripting at Scale
- Performance Optimization
- Measuring Execution Time
On this page
Measuring PowerShell Scripts Execution Time: Complete Guide
Updated on June 25, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Accurate performance measurement is the foundation of effective PowerShell optimization. The Measure-Command cmdlet is the primary tool for timing script execution, providing precise elapsed time measurements down to the millisecond. For scenarios requiring more control or progress reporting during long-running operations, the .NET Stopwatch class offers additional flexibility. By understanding when to use each method and following best practices—such as running multiple iterations and accounting for environmental variability—you can reliably identify bottlenecks and validate performance improvements across your automation scripts.
Why Measure Execution Time​
Performance measurement allows you to:
- Identify bottlenecks — pinpoint slow sections of code that impact overall execution
- Compare implementations — evaluate alternative approaches objectively
- Detect regressions — catch performance degradation after code changes
- Validate improvements — confirm that optimizations have the desired effect
- Estimate scale — predict how scripts will perform with larger datasets
Without measurement, optimization becomes guesswork. With it, you can make informed, data-driven decisions.
Using Measure-Command​
Measure-Command is the primary cmdlet for timing PowerShell code. It runs a script block or cmdlet internally, times the execution, and returns a TimeSpan object containing the elapsed time.
Basic Syntax​
Measure-Command { Get-Process }
Code explanation: Measure-Command accepts a script block enclosed in curly braces. It executes the block and records the elapsed time. The output is a TimeSpan object with properties such as TotalMilliseconds, TotalSeconds, Days, Hours, Minutes, Seconds, and Ticks.
Example Output​
Measure-Command { Get-Process }
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 125
Ticks : 1254321
TotalDays : 1.45175925925926E-06
TotalHours : 3.48422222222222E-05
TotalMinutes : 0.00209053333333333
TotalSeconds : 0.1254321
TotalMilliseconds : 125.4321
Code explanation: The cmdlet returns a rich TimeSpan object. TotalMilliseconds is the most commonly used metric for performance comparisons.
Comparing Two Approaches​
A common use case is comparing the performance of different implementations:
# Using -Path with wildcard
Measure-Command { Get-ChildItem -Path C:\Windows\*.txt -Recurse }
# Using -Filter parameter (provider-specific filter)
Measure-Command { Get-ChildItem C:\Windows -Filter "*.txt" -Recurse }
Code explanation: The -Filter parameter is often faster because filtering happens at the provider level rather than after all items are retrieved. This example demonstrates how measurement can reveal performance differences between seemingly similar approaches.
Piping Input to Measure-Command​
Objects piped to Measure-Command are available to the script block via the $_ variable:
10, 20, 50 | Measure-Command -Expression {
for ($i = 0; $i -lt $_; $i++) { $i }
}
Code explanation: The script block executes once for each object in the pipeline.
Displaying Output During Measurement​
By default, Measure-Command suppresses output from the measured command. To display output while still measuring time, pipe to Out-Default:
Measure-Command { Get-Process | Out-Default }
Code explanation: Out-Default sends output to the console while the measurement still captures the execution time.
Understanding the Output​
The result of Measure-Command is a TimeSpan object. Key properties include:
PropertyDescriptionTotalMillisecondsTotal elapsed time in milliseconds (most commonly used)TotalSecondsTotal elapsed time in secondsTotalMinutesTotal elapsed time in minutesTicksThe smallest measurable unit (1 tick = 100 nanoseconds)Days, Hours, Minutes, Seconds, MillisecondsIndividual components of the elapsed time
To capture the result for later use:
$time = Measure-Command { Get-ADUser -Filter * }
Write-Output "Execution time: $($time.TotalSeconds) seconds"
Using the .NET Stopwatch Class​
For scenarios requiring more control—such as measuring elapsed time with progress reporting or pausing and resuming timers—the .NET Stopwatch class provides a powerful alternative.
Basic Stopwatch Usage​
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
# Code to measure
Start-Sleep -Seconds 2
$stopwatch.Stop()
$elapsed = $stopwatch.Elapsed
Write-Output "Elapsed: $($elapsed.TotalMilliseconds) ms"
Code explanation: [System.Diagnostics.Stopwatch]::StartNew() creates and starts a new stopwatch instance. After executing the code, Stop() ends the timing. The Elapsed property returns a TimeSpan object.
Stopwatch Methods​
MethodDescriptionStartNew()Creates and starts a new stopwatchStart()Starts timingStop()Stops timingReset()Resets elapsed time to zeroRestart()Resets and starts timing again
Progress Reporting with Stopwatch​
A key advantage of Stopwatch is the ability to report progress during long-running operations:
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
foreach ($item in $largeCollection) {
# Process item
if ($stopwatch.Elapsed.TotalSeconds -gt 30) {
Write-Output "Still running... elapsed: $($stopwatch.Elapsed.TotalSeconds) seconds"
$stopwatch.Restart()
}
}
Code explanation: The Restart() method resets and restarts the timer, allowing you to report progress at regular intervals without losing the ability to measure total time.
Stopwatch vs. Measure-Command​
FeatureMeasure-CommandStopwatchEase of useSimple, one-lineRequires more codeOutput suppressionAutomaticManualProgress reportingNot built-inYes, with Stop()/Restart()GranularityMillisecond precisionHigh precisionBest forQuick benchmarksComplex timing scenariosScope impactModifies current scopeNo scope impact
Note: For micro-benchmarking of small code blocks,
Measure-Commandmay show variation due to overhead. TheStopwatchclass can be more suitable for such scenarios.
Using Get-Date Timestamps​
For long-running operations where Measure-Command may be impractical, timestamps provide a straightforward alternative:
$start = Get-Date
# Long-running task
Start-Sleep -Seconds 5
$end = Get-Date
$duration = $end - $start
Write-Output "Duration: $duration"
Code explanation: Get-Date captures the current time. Subtracting the start from the end produces a TimeSpan object.
Performance Consideration​
Get-Date has slightly higher overhead than [System.DateTime]::Now, though both are well under a millisecond. For most administrative scripts, the difference is negligible.
Measuring Repeated Executions​
Single measurements can be misleading due to:
- Caching effects
- Background system activity
- Network fluctuations
- JIT compilation
To obtain reliable results, run the code multiple times and average the results:
$iterations = 10
$results = 1..$iterations | ForEach-Object {
(Measure-Command { Get-Service }).TotalMilliseconds
}
$average = ($results | Measure-Object -Average).Average
$min = ($results | Measure-Object -Minimum).Minimum
$max = ($results | Measure-Object -Maximum).Maximum
Write-Output "Average: $average ms, Min: $min ms, Max: $max ms"
Code explanation: This runs the command 10 times, collecting each measurement. Measure-Object calculates the average, minimum, and maximum. The average provides the most reliable estimate of typical performance.
Measuring Pipeline Performance​
Pipelines are expressive but can introduce overhead. Comparing pipeline and non-pipeline approaches helps identify the most efficient implementation:
Pipeline Approach​
Measure-Command {
Get-ChildItem C:\Windows | Where-Object { $_.Length -gt 1MB }
}
Non-Pipeline Approach​
Measure-Command {
foreach ($file in Get-ChildItem C:\Windows) {
if ($file.Length -gt 1MB) { $file }
}
}
Code explanation: The non-pipeline approach using foreach can be faster for large datasets because it avoids the overhead of creating pipeline objects for each item. Measurement allows you to choose the best approach for your specific scenario.
Measuring Remote Execution Time​
When working with remote systems, network latency affects performance:
Measure-Command {
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service }
}
Code explanation: The measurement includes network round-trip time, providing a realistic estimate of performance in distributed environments.
Scope Considerations​
By default, Measure-Command runs the script block in the current scope. This means variables set inside the script block will affect the current scope:
$foo = 'Value 1'
$null = Measure-Command { $foo = 'Value 2' }
$foo # Returns 'Value 2'
Code explanation: The script block modifies $foo in the current scope because Measure-Command does not create a child scope.
To avoid modifying the current scope, wrap the script block in braces and use the invocation operator (&):
$foo = 'Value 1'
$null = Measure-Command { & { $foo = 'Value 2' } }
$foo # Returns 'Value 1'
Code explanation: The & operator executes the inner script block in a child scope, preventing changes to the parent scope.
Best Practices for Performance Measurement​
Run Multiple Iterations​
A single measurement can be skewed by system variability. Run the code multiple times and use the average.
Measure Under Realistic Conditions​
Test with data sizes, network conditions, and system loads similar to production.
Isolate the Code Being Measured​
Minimize external factors by closing other applications and running tests on dedicated systems when possible.
Avoid Measuring in Busy Environments​
Unless your production environment is consistently busy, measure during periods of low activity to get baseline performance.
Use Appropriate Precision​
For sub-millisecond measurements, use Stopwatch rather than Measure-Command.
Document Measurement Conditions​
Record the PowerShell version, operating system, hardware, and data size when documenting performance results.
Summary​
Measuring execution time is essential for writing efficient PowerShell scripts. PowerShell provides several tools for this purpose:
Measure-Command— the primary cmdlet for timing script blocks- .NET
Stopwatchclass — for granular control and progress reporting Get-Datetimestamps — for long-running operations
By mastering these techniques and following best practices—such as running multiple iterations and accounting for environmental variability—you gain the ability to evaluate performance objectively and optimize your scripts with confidence.
Pro Tip: When comparing two approaches, always use the same measurement method and run multiple iterations. The goal is not just to know which is faster, but to understand by how much and whether the difference matters in your specific context.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Performance Optimization
Next
Pipeline Optimization
-
Why Measure Execution Time
-
Using Measure-Command
- Basic Syntax
- Example Output
- Comparing Two Approaches
- Piping Input to Measure-Command
- Displaying Output During Measurement
-
Understanding the Output
-
Using the .NET Stopwatch Class
- Basic Stopwatch Usage
- Stopwatch Methods
- Progress Reporting with Stopwatch
- Stopwatch vs. Measure-Command
-
Using Get-Date Timestamps
- Performance Consideration
-
Measuring Repeated Executions
-
Measuring Pipeline Performance
- Pipeline Approach
- Non-Pipeline Approach
-
Measuring Remote Execution Time
-
Scope Considerations
-
Best Practices for Performance Measurement
- Run Multiple Iterations
- Measure Under Realistic Conditions
- Isolate the Code Being Measured
- Avoid Measuring in Busy Environments
- Use Appropriate Precision
- Document Measurement Conditions
-
Summary
