A useful link to refer to later: WMI Query language examples.
PowerShell can access WMI via Get-WMIObject
. And while it’s easier to just pull all WMI objects and then filter, it’s faster if you do the filtering while pulling itself.
Case in hand: getting a list of installed drivers. The Win32_PnpSignedDriver
WMI class is what you need to tap into for this. Like thus:
1 |
Get-WMIObject -Class Win32_PnPSignedDriver |
This gives a bucket-load of output. If you want to filter out just a particular driver, the easy way is this:
1 |
Get-WMIObject -Class Win32_PnPSignedDriver | ?{ $_.DeviceName -like "*PCI*" } |
The better way, though, is to use WMI queries and filter while running WMI itself. Like this:
1 |
Get-WMIObject -Class Win32_PnPSignedDriver -Filter "DeviceName like '%PCI%'" |
Both return the same number of results:
1 2 3 4 |
PS> (Get-WMIObject -Class Win32_PnPSignedDriver | ?{ $_.DeviceName -like "*PCI*" }).Count 17 PS> (Get-WMIObject -Class Win32_PnPSignedDriver -Filter "DeviceName like '%PCI%'").Count 17 |
But the latter is faster.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
PS> Measure-Command -Expression { Get-WMIObject -Class Win32_PnPSignedDriver | ?{ $_.DeviceName -like "*PCI*" } } Days : 0 Hours : 0 Minutes : 0 Seconds : 1 Milliseconds : 637 Ticks : 16374688 TotalDays : 1.89521851851852E-05 TotalHours : 0.000454852444444444 TotalMinutes : 0.0272911466666667 TotalSeconds : 1.6374688 TotalMilliseconds : 1637.4688 PS> Measure-Command -Expression { Get-WMIObject -Class Win32_PnPSignedDriver -Filter "DeviceName like '%PCI%'" } Days : 0 Hours : 0 Minutes : 0 Seconds : 1 Milliseconds : 593 Ticks : 15936620 TotalDays : 1.8445162037037E-05 TotalHours : 0.000442683888888889 TotalMinutes : 0.0265610333333333 TotalSeconds : 1.593662 TotalMilliseconds : 1593.662 |
The difference isn’t much in the example above, but when you run this across the network for multiple computers it adds up quickly.
So when in doubt filter at the WMI level. And to make filter queries like the above, the link at the start of this post helps. It gives you the keywords you can use. Like, for instance, to do wildcard matches use the like
keyword as above. And like *
is the wildcard symbol usually, for WMI queries %
is the wildcard symbol. Similarly, to do exact matches use the =
keyword; to do relational matches (greater than, less than) use the <
and >
keywords; and so on.
Special shout-out to this blog post where I first came across the like
keyword.