Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Filter Left

Posted on October 14, 2011October 14, 2011

When writing WMI queries expressions in Windows PowerShell, it is recommended to use WMI filtering, as opposed to getting objects and then filtering with Where-Object. I see expressions like this quite often:
[cc lang="PowerShell"]
get-wmiobject win32_process -computer $c | where {$_.name -eq "notepad.exe"}
[/cc]
In this situation, ALL process objects are retrieved and THEN filtered. The better performing approach is to use a WMI filter:
[cc lang="PowerShell"]
get-wmiobject win32_process -filter "name='notepad.exe'" -computer $c
[/cc]
The WMI service on the remote computer filters in place and you only get back the item you want. Don't believe me? Measure for yourself. Start up Notepad, then define these script blocks.
[cc lang="PowerShell"]
PS C:\> $a={gwmi win32_process | where {$_.name -eq "notepad.,exe"}
PS C:\> $b={gwmi win32_process -filter "name='notepad.,exe'"}
[/cc]
Now measure how long it takes the first to run:
[cc lang="PowerShell"]
PS C:\> Measure-command $a
[/cc]
WMI caches results so wait about 10 minutes and then measure the second script block.
[cc lang="PowerShell"]
PS C:\> Measure-command $b
[/cc]
For me, the second expression took half as long. Granted this is a small data set and I'm not going to quibble over 100ms. But when you think about querying many computers with the potential for larger data sets, the performance gains are significant. So get in the habit of filtering as far to the left as you can in your PowerShell expressions.

[this was originally posted in my Google+ account.]

Share this:

  • Print (Opens in new window) Print

Like this:

Like Loading…

Related

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2026 The Lonely Administrator | Powered by SuperbThemes!
%d