PS: Using Multiple Filters in Get-WMIObject to improve WMI query performances

It’s very often we require to filter WMI query results with multiple filters.  For example, you want to get all services whose startup type is set to Manual and that are running.  Most usual practice that all use is to apply where-object filtering on getting the all the results from WMI query.  This isn’t effective since you are fetching all results from WMI query and then applying filtering on top the query results.  Instead one can fine tune the initial WMI query itself to result only in required data so that we again don’t need to run the where-objects filtering.  This also improves the query/cmdlets performance in execution as  shown below. However, a multiple filters query building for WMI is not known for many people and thus I am putting a simple example with details the syntax and also shows performance improvement.

 

 

Usual Where-Object filtering on top of WMI results set

PS C:> Get-WmiObject -Class win32_service | where-object { ($_.StartMode -eq "Manual") -and ($_.State -eq "Running") }
| Measure | select count | ft -a

Count
—–
   18

PS C:>

 

WMI query with multiple filters to fetch only required details

PS C:> Get-WmiObject -Class win32_service -Filter "StartMode=’Manual’ and State=’Running’" | Measure | select count | ft -a

Count
—–
   18

PS C:>

 

Performance difference with using multiple WMI filters instead of where-object filtering

 

PS C:> Measure-Command { Get-WmiObject -Class win32_service | where-object { ($_.StartMode -eq "Manual") -and ($_.State -eq "Running") } } | select TotalSeconds | ft -a

TotalSeconds
————
0.5028714

PS C:> Measure-Command { Get-WmiObject -Class win32_service -Filter "StartMode=’Manual’ and State=’Running’" } | Select TotalSeconds | ft -a

TotalSeconds
————
0.2707537

PS C:>

2 thoughts on “PS: Using Multiple Filters in Get-WMIObject to improve WMI query performances

  1. tried your command on windows 7 and windows 2008 R2. It fails

    Get-WmiObject : Invalid query
    At line:1 char:14
    + Get-WmiObject <<<< -Class win32_service -Filter "StartMode='Manual' and State='Running'"
    + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObject
    Command

    1. Well, I figured out the issue. When you copy over the query from the article it’s changing the Quote character(‘). Just try deleting the ‘ character and typing again from the keyboard. Then the query should work for you.

Leave a Reply

Your email address will not be published. Required fields are marked *