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.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
[this was originally posted in my Google+ account.]