Using AD Filters with Cmdlets (Part 2)

by Aug 1, 2018

In the previous tip we started to look at how cmdlets from the ActiveDirectory module (part of the free RSAT tools) can filter results. You learned that the filters look like PowerShell code but in reality, they are not.

For simple queries, the filters work well. However, once you use PowerShell language features other than operators, you will soon discover that the filter in reality is not using PowerShell code.

If you’d like to get a list of AD users with no profilepaths, you’d probably be intrigued to try one of these lines:

 
Get-ADUser -Filter { profilePath -eq $null} -ResultSetSize 5
Get-ADUser -Filter { profilePath -eq ''} -ResultSetSize 5
 

Both filters fail. PowerShell complains that the variable $null is unknown, and in the second line, that the search query was invalid.

This is why in most cases it is much easier (and faster) to use the native LDAPFilters that are common place in Active Directory. LDAP filters are expressions in parenthesis. They contain an attribute name, and an operator. This gets you the first 5 users that have a profilepath:

 
Get-ADUser -LDAPFilter '(profilePath=*)' -ResultSetSize 5 
 

By using a „!“, you can invert the result, so this gets you the first five users with NO profile path:

 
Get-ADUser -LDAPFilter '(!profilePath=*)' -ResultSetSize 5 
 

And this would dump a list of users and their profile paths:

 
Get-ADUser -LDAPFilter '(profilePath=*)' -Properties profilePath | 
Select-Object samaccountName, profilePath 
 

Twitter This Tip! ReTweet this Tip!