Check PowerShell Speed

by Jun 19, 2012

To find out how much time a particular cmdlet or command takes, here's a handy little stopwatch that you can use:

function Test {
  $codetext = $Args -join ' '
  $codetext = $ExecutionContext.InvokeCommand.ExpandString($codetext)

  $code = [ScriptBlock]::Create($codetext)

  $timespan = Measure-Command $code
  "Your code took {0:0.000} seconds to run" -f $timespan.TotalSeconds

Now, to find out the performance of a particular command, try this:

PS> test Get-Service
Your code took 0,004 seconds to run

PS> test Get-WmiObject Win32_Service
Your code took 0,445 seconds to run

This can be especially useful if you have two cmdlets or parameters that apparently do the same. Performance difference can be tremendous, though:

PS> test dir $home -Include *.ps1 -Recurse
Your code took 5,741 seconds to run

PS> test dir $home -Filter *.ps1 -Recurse
Your code took 0,894 seconds to run

To test drive more complex commands, make sure you place them in quotes.

Twitter This Tip! ReTweet this Tip!