How to Measure Script Execution Time in Windows 11 Using PowerShell Measure-Command

When developing automation scripts, querying Active Directory, or migrating large file repositories in Windows 11, measuring execution duration is essential for identifying bottlenecks. Relying on stopwatch timers or manual timestamps produces imprecise benchmarks that fail to capture millisecond-level code performance differences.

Windows PowerShell includes a native benchmarking cmdlet called Measure-Command. Operating similarly to the Unix time utility, Measure-Command executes any script block, pipeline, or external executable and measures the internal elapsed time with high precision, returning a structured TimeSpan object. You can use it alongside other administrative tasks, such as learning how to find duplicate files with PowerShell or audit startup applications with PowerShell.

How Measure-Command Works

The Measure-Command cmdlet takes an expression enclosed inside curly braces { ... } as an execution script block. While the code executes, PowerShell records internal system ticks and outputs a detailed breakdown across multiple time increments:

  • Days, Hours, Minutes, Seconds, Milliseconds: Discrete breakdown of elapsed units.
  • Ticks: The number of 100-nanosecond intervals elapsed.
  • TotalSeconds / TotalMilliseconds: Floating-point cumulative values ideal for logging and comparative analysis.

Measuring Single Commands and Built-In Cmdlets

To measure how long a basic administrative command takes to run, enclose the command inside script block brackets:

  1. Open Windows Terminal or PowerShell (press Win + X and choose Terminal).
  2. Run Measure-Command followed by your target command. For example, to benchmark recursive file enumeration across your user profile:
    Measure-Command { Get-ChildItem -Path "C:\Users\username\Documents" -Recurse }
  3. PowerShell executes the directory traversal and outputs the diagnostic summary:
    Days              : 0
    Hours             : 0
    Minutes           : 0
    Seconds           : 2
    Milliseconds      : 412
    Ticks             : 24128914
    TotalDays         : 2.79269837962963E-05
    TotalHours        : 0.000670247611111111
    TotalMinutes      : 0.0402148566666667
    TotalSeconds      : 2.4128914
    TotalMilliseconds : 2412.8914

Measuring Multi-Line Automation Scripts and Loops

You can benchmark complex multi-step scripts by placing multiple statements inside the script block:

Measure-Command {
    $processes = Get-Process
    $sorted = $processes | Where-Object { $_.WorkingSet -gt 50MB } | Sort-Object WorkingSet -Descending
    $sorted | Select-Object -First 10 ProcessName, WorkingSet
}

Filtering and Extracting Specific Time Metrics

Because Measure-Command outputs a standard .NET System.TimeSpan object, you can select specific properties for clean, automated logging:

$time = Measure-Command { Invoke-WebRequest -Uri "https://digitash.com" -UseBasicParsing }
Write-Host "HTTP Response Time: $($time.TotalMilliseconds) ms"

Measuring External Binaries (.exe)

You can also benchmark standard Windows command-line utilities (such as robocopy, ping, or git) using the call operator &:

Measure-Command { & robocopy "C:\Source" "D:\Backup" /E /MT:8 }

Handling Command Output (Why Does the Terminal Go Blank?)

By design, Measure-Command suppresses the standard output stream of whatever command is running inside the block so that screen-rendering delays (the time it takes the console window to render thousands of lines of text) do not skew your underlying computational benchmarks.

If your script strictly requires capturing both the pipeline output and the execution duration, use the Out-Default cmdlet or store intermediate data in a variable:

$results = $null
$elapsed = Measure-Command {
    $script:results = Get-Service | Where-Object { $_.Status -eq "Running" }
}
Write-Host "Discovered $($results.Count) active services in $($elapsed.TotalSeconds) seconds."

Comparing Two Alternative Approaches (Benchmarking Optimization)

When optimising PowerShell automation, Measure-Command provides objective data to compare syntax efficiency. For example, testing array filtering using Where-Object versus the optimized .Where{} method:

$data = 1..100000

$time1 = Measure-Command { $data | Where-Object { $_ % 2 -eq 0 } }
$time2 = Measure-Command { $data.Where({ $_ % 2 -eq 0 }) }

Write-Host "Pipeline filter: $($time1.TotalMilliseconds) ms"
Write-Host "Method filter:   $($time2.TotalMilliseconds) ms"

This comparison reveals that the .Where{} method processes the dataset several times faster than pipeline iterations.

Frequently Asked Questions

Does Measure-Command include background thread execution?

No. Measure-Command benchmarks synchronous execution on the current thread. If your script launches asynchronous jobs using Start-Job or Start-ThreadJob, it measures only the time required to dispatch the job, not the time taken for background threads to complete, unless you include Wait-Job within the block.

Can I export Measure-Command results to CSV?

Yes. Pipe the output to Select-Object and Export-Csv:

Measure-Command { Get-Process } | Select-Object TotalMilliseconds, TotalSeconds, Ticks | Export-Csv -Path "benchmark.csv" -NoTypeInformation

How does Measure-Command differ from the Stopwatch class?

Measure-Command is essentially a friendly wrapper around the .NET [System.Diagnostics.Stopwatch] class. While Measure-Command is ideal for single-block timing, advanced developers can use [System.Diagnostics.Stopwatch]::StartNew() for complex scripts requiring multiple pause, lap, or split timestamps.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.