Filtering

Uncategorized

I’ve been grading the scripts in the warm up events for the Scripting Games and noticed a lot of people doing this:

Get-WmiObject -Class Win32_LogicalDisk | where {$_.DriveType -eq 3}

Ok now it works but there are a couple of things wrong with this approach.

Firstly, you are ignoring the built in capabilities of the get-wmiobject cmdlet

PS> Get-Command Get-WmiObject -Syntax

Get-WmiObject [-Class] <string> [[-Property] <string[]>] [-Filter <string>] [-Amended] [-DirectRead] [-AsJob]
[-Impersonation <ImpersonationLevel>] [-Authentication <AuthenticationLevel>] [-Locale <string>]
[-EnableAllPrivileges] [-Authority <string>] [-Credential <pscredential>] [-ThrottleLimit <int>] [-ComputerName
<string[]>] [-Namespace <string>] [<CommonParameters>]

Get-WmiObject [[-Class] <string>] [-Recurse] [-Amended] [-List] [-AsJob] [-Impersonation <ImpersonationLevel>]
[-Authentication <AuthenticationLevel>] [-Locale <string>] [-EnableAllPrivileges] [-Authority <string>] [-Credential
<pscredential>] [-ThrottleLimit <int>] [-ComputerName <string[]>] [-Namespace <string>] [<CommonParameters>]

Get-WmiObject -Query <string> [-Amended] [-DirectRead] [-AsJob] [-Impersonation <ImpersonationLevel>] [-Authentication
<AuthenticationLevel>] [-Locale <string>] [-EnableAllPrivileges] [-Authority <string>] [-Credential <pscredential>]
[-ThrottleLimit <int>] [-ComputerName <string[]>] [-Namespace <string>] [<CommonParameters>]

Get-WmiObject [-Amended] [-AsJob] [-Impersonation <ImpersonationLevel>] [-Authentication <AuthenticationLevel>]
[-Locale <string>] [-EnableAllPrivileges] [-Authority <string>] [-Credential <pscredential>] [-ThrottleLimit <int>]
[-ComputerName <string[]>] [-Namespace <string>] [<CommonParameters>]

Get-WmiObject [-Amended] [-AsJob] [-Impersonation <ImpersonationLevel>] [-Authentication <AuthenticationLevel>]
[-Locale <string>] [-EnableAllPrivileges] [-Authority <string>] [-Credential <pscredential>] [-ThrottleLimit <int>]
[-ComputerName <string[]>] [-Namespace <string>] [<CommonParameters>]

Notice the filter parameter in the first parameter set.

When you run Get-WMIObject in effect you are running a WQL query

“SELECT * FROM Win32_LogicalDisk”

if you move the filter into the query it changes to

“SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3”

This is coded in the cmdlet as

Get-WmiObject -Class Win32_LogicalDisk -Filter “DriveType = 3″

Why is this better?

Because you are doing less work against the WMI repository – therefore more efficient.

Also if you are running against a remote machine filtering in the WMI query means you bring less data back across the network which makes you whole process more efficient.

Bottom line – filter as early as you sensibly can and preferably on the remote machine.

Comments are closed.