Categories

Filtering AD searches

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

Leave a Reply