Time Code With a Stopwatch in PowerShell

Measure elapsed time with the .NET Stopwatch class.

WindowsTerminalscriptingpowershellLow risk
Run the snippet to start, stop and print elapsed time.

01Command

Command
$ $sw=[Diagnostics.Stopwatch]::StartNew(); Start-Sleep -Seconds 2; $sw.Stop(); $sw.Elapsed

02What it does

StartNew creates and starts a high-resolution Stopwatch; call Stop and read Elapsed for a TimeSpan. Unlike Measure-Command, it can be started and stopped multiple times, so it is useful for timing individual sections of a longer script.

03Risk

RiskLow risk
RequirementsWindows 10/11 with PowerShell 5.1 or PowerShell 7+
!Warning: Stopwatch measures wall-clock elapsed time; for CPU time use Measure-Command or process counters instead.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

  • Stopwatch Class
    Microsoft Learn · vendor-doc · 2026-09-20
    Evidence: High-resolution .NET stopwatch used to measure elapsed time.

Last verified: 2026-09-20 · Category: Developer

06Related solutions