PowerShell for Windows Admins

Aug 30 2013   11:09AM GMT

Filtering AD searches



Posted by: Richard Siddaway
Tags:
Active Directory
PowerShell

Interesting question came up regarding how you define a Filter when you are searching for particular users. With the Microsoft cmdlets you can define a filter or an ldapfilter.

In these examples we’re looking for users that don’t have email addresses. First lets look at a filter

PS> Get-ADUser -Filter {mail -notlike “*”} | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
776 user

The filter is looking for any user accounts that have a mail attribute that isn’t like any characters – in otherwords empty. The advantage of using the –Filter parameter is that the syntax is easy and is what you’re used to in other PowerShell cmdlets such as Where-Object.

The LDAP filters get a bit more complicated

PS> Get-ADUser -LDAPFilter “(&(objectCategory=user)(!mail=*))” | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
776 user

Same results but the filter is much more difficult to understand

“(&(objectCategory=user)(!mail=*))”

& means AND

! means NOT

so this reads as

objectcategory=user AND NOT(mail = anything)

The advantage to using an LDAP filter is that you can re-use it on the GUI tools or directorysearcher

You need to be careful if you use Get-ADObject instead of Get-ADUser. Using the same LDAPFilter as above is fine

PS> Get-ADObject -LDAPFilter “(&(objectCategory=user)(!mail=*))” | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
776 user

but if you change objectcategory to objectclass which seems reasonable you get very different results:

PS> Get-ADObject -LDAPFilter “(&(objectClass=user)(!mail=*))” | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
30 computer
776 user
2 msDS-ManagedServiceAcc…
1 msDS-GroupManagedServi…

Huh! – Computers?

This because computers, users and managed service accounts all derive from the same AD schema class – users BUT they have different objectcategories to separate them.

There’ll be a lot more on searching AD and LDAP filters in AD management in a month of lunches – www.manning.com/siddaway3

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: