Use Server-Side Filtering When Possible

by Nov 6, 2015

When you retrieve information across a network, always make sure you use client-side techniques like Where-Object as a last resort. Server-side filtering is much more efficient.

For example, when you are trying to find users with a defined mail address, using a client-side Where-Object statement would push all AD users to your machine, and only then would Where-Object identify the ones you need:

#requires -Version 1 -Modules ActiveDirectory

# inefficient client-side filter
Get-ADUser -Filter * | Where-Object { $_.mail -ne $null }

As you guessed, whenever a cmdlet has a parameter called -Filter, it can be used to filter the needed elements on the server-side before they travel to your machine. However, the -Filter parameter found In Get-ADUser sometimes works awkwardly, trying to turn PowerShell-like syntax into the LDAP queries needed by Active Directory.

So often, it is just more convenient to use LDAP query strings in the first place. These two statements would quickly find all user accounts that either have (any) email address defined, or have none:

#requires -Version 1 -Modules ActiveDirectory

# any user with a mail address
Get-ADUser -LDAPFilter '(mail=*)'

# any user with NO mail address
Get-ADUser -LDAPFilter '(!mail=*)'

Twitter This Tip! ReTweet this Tip!