Prof. Powershell

Do You Measure Up?

Use the Measure-Command cmdlet to get a better idea of your Powershell efficiency.

I frequently get questions about the best way to construct a PowerShell expression. To be certain, there are ways to optimize your command, especially when doing filtering over a large data set. But how can you know if one technique is more efficient than another? Get hard numbers using the Measure-Command cmdlet:

PS C:\> measure-command {get-eventlog system -newest 50}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 224
Ticks             : 2247086
TotalDays         : 2.60079398148148E-06
TotalHours        : 6.24190555555556E-05
TotalMinutes      : 0.00374514333333333
TotalSeconds      : 0.2247086
TotalMilliseconds : 224.7086

The cmdlet will execute whatever is entered in the curly braces and return a TimeSpan object that shows how long the expression took to complete. You won't see the result of the script block expression, only how long it took to complete. The output you see are properties of the resulting TimeSpan object, which means you can do something like this:

PS C:\> (measure-command {dir c:\scripts -recurse | Where {$_.extension -match ".vbs"}}).TotalSeconds


This expression, getting a recursive directory listing of all files in C:\scripts where the extension is .vbs, took almost 18 seconds to complete. That seems long to me and I know that Get-Childitem, (I used its alias dir) has a -filter parameter. Let's see if it makes a difference:

PS C:\> (measure-command {dir c:\scripts -recurse -filter *.vbs}).TotalSeconds


Sure enough, doing filtering with the first cmdlet is more efficient. This time I got results in 1.7 seconds. But the point I'm making is that by using Measure-Command, I got hard data to backup my assumption.

One last thing: Be sure you test your command and verify it gets the results you intend before you use Measure-Command. Since you don't see the output, you also don't see any error messages.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular