brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Measure-Command times any PowerShell command

Scripting
~/tips/tip-windows-measure-command

Measure-Command { Get-ChildItem -Path C:\Windows\*.txt -Recurse }

Runs a PowerShell command and reports how long it took to finish.

When two PowerShell commands do the same job, I want to know which one is faster before I put it in a script. Measure-Command answers that: it runs a script block and tells you how long it took.

Microsoft’s own example is a good one, comparing a recursive search with -Path against one with the provider’s -Filter parameter:

Measure-Command { Get-ChildItem -Path C:\Windows\*.txt -Recurse }
Measure-Command { Get-ChildItem C:\Windows -Filter "*.txt" -Recurse }

Each one returns a TimeSpan with Days, Hours, Minutes, Seconds and Milliseconds, plus totals like TotalSeconds. In the docs, the -Filter version wins by a wide margin, which is a nice lesson on its own. If you only want the number, wrap it:

(Measure-Command { Get-ChildItem C:\Windows -Filter "*.txt" -Recurse }).TotalSeconds

Two caveats catch people out. First, the output of the command inside the braces disappears; you only see the timing. Pipe it to Out-Default inside the script block if you want to see both. Second, the script block runs in the current scope, not a child scope, so a variable you change inside it stays changed afterwards. Wrap the block as { & { ... } } to run it in a child scope instead.

I’d also run a measurement a few times before drawing conclusions. A file search can be slower the first time, while nothing is cached yet, so one number on its own can fool you.

Further reading: Measure-Command (Microsoft Learn)

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile from collections import Counter import shutil All Scripting tips (10) All topics

Link