Active Directory Powershell – Advanced Filter (Part – II)

In my previous post I discussed about the various features available in -Filter parameter aka “advanced filter”. This post extends the previous one and discusses about the various operators supported in Advanced Filter and also give examples using each one of them. Most of the examples are picked from our on-the-box help, which you can access by typing:

PS C:\> get-help about_ActiveDirectory_Filter   ## this works only in newer builds

Here is the list of supported operators in Active Directory Powershell Advanced Filter:

 

Logical Operator Description Equivalent LDAP operator/ expression
-eq Equal to. This will not support wild card search. =
-ne Not equal to. This will not support wild card search. ! x = y
-like Similar to -eq and supports wildcard comparison. The only wildcard character supported is: * =
-notlike Not like. Supports wild card comparison. ! x = y
-approx Approximately equal to ~=
-le Lexicographically less than or equal to <=
-lt Lexicographically less than ! x >= y
-ge Lexicographically greater than or equal to >=
-gt Lexicographically greater than ! x <= y
-and AND &
-or OR |
-not NOT !
-bor Bitwise OR :1.2.840.113556.1.4.804:=
-band Bitwise AND :1.2.840.113556.1.4.803:=
-recursivematch Uses LDAP_MATCHING_RULE_IN_CHAIN (Win2k3 SP2 and above) :1.2.840.113556.1.4.1941:=

 

Example 1: Get all entries
        Get-ADObject -Filter { ObjectClass -like "*" }

        LDAP Filter Equivalent: (objectClass=*)

Example 2: Get entries containing "bob" somewhere in the common name
        Get-ADObject -Filter { CN -like "*bob*" }

        LDAP Filter Equivalent:  (cn=*bob*)

Example 3: Get entries with a bad password count greater than five
        Get-ADUser -Filter { badpwdcount -ge 5 }

        LDAP Filter Equivalent: (badpwdcount>=5)

Example 4: Get all users with an e-mail attribute
        Get-ADUser -filter { email -like "*" }        -or-        Get-ADObject -filter { email -like "*" -and ObjectClass -eq "user" }

        LDAP Filter Equivalent: (&(objectClass=user)(email=*))

Example 5: Get all user entries with an e-mail attribute and a surname equal to "smith"
        Get-ADUser -Filter { Email -like "*" -and Surname -eq "smith" }        -or-        Get-ADUser -Filter { Email -like "*" -and sn -eq "smith" }

        LDAP Filter Equivalent: (&(sn=smith)(objectClass=user)(email=*))

Example 6: Get all user entries with a common name that starts with "andy" and users with a common name of "steve" or "margaret"
        Get-ADUser -Filter { CN -like "andy*" -or CN -eq "steve" -or CN -eq "margaret" }        -or-        Get-ADObject -Filter { objectClass -eq "user" -and (CN -like "andy*" -or CN -eq "steve" -or CN -eq "margaret") }

        LDAP Filter Equivalent: (&(objectClass=user) | (cn=andy*)(cn=steve)(cn=margaret))

Example 7: Get all entries without an e-mail attribute
        Get-ADUser -Filter { -not Email -like "*" }        -or-        Get-ADUser -Filter { Email -notlike "*" }

        LDAP Filter Equivalent: (!(email=*))

Example 8: Get all users who did not logon since January 1, 2007
        $date = new-object System.DateTime -ArgumentList @(2007,1,1,0,0,0)        Get-ADUser -Filter { -not LastLogon -le $date }

        LDAP Filter Equivalent:  (&(lastlogon<=X)(objectClass=user))        ## where X is number of 100-nanosecond slices since Jan 1st 1601

Example 9: Get all users who have logged on in the last 5 days
        $date = (get-date) - (new-timespan -days 5)        Get-ADUser -Filter { lastLogon -gt $date }

        LDAP Filter Equivalent:  (&(lastLogon>=128812906535515110) (objectClass=user)(!(objectClass=computer)))

Example 10: Get all security groups
The following example query string searches for group objects that have the ADS_GROUP_TYPE_SECURITY_ENABLED flag (0x80000000 = 2147483648) set.
        Get-ADGroup -filter { groupType -band 0x80000000 }        -or-        Get-ADGroup -filter { GroupCategory -eq "Security" }

        LDAP Filter Equivalent: (&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=2147483648))

Example 11: Check if a user is a member of a group (recursively)
The following example query string uses the LDAP_MATCHING_RULE_IN_CHAIN, which is a matching rule OID that is designed to provide a method to look up the ancestry of an object.

        Get-ADUser -Filter { memberOf -RecursiveMatch "CN=Administrators,CN=Builtin,DC=Fabrikam,DC=com" } -SearchBase "CN=Administrator,CN=Users,DC=Fabrikam,DC=com"  -SearchScope Base                      ## NOTE: The above command will return the user object (Administrator in this case) if it finds a match recursively in memberOf attribute.         -or-        $userObj = Get-ADUser Administrator        $groupObj = Get-ADUser Administrators        Get-ADUser -Filter { memberOf -RecursiveMatch $userObj.DistinguishedName } -SearchBase $groupObj.DistinguishedName -SearchScope Base

        LDAP Filter Equivalent: (memberof:1.2.840.113556.1.4.1941:=(CN=Administrators,CN=Builtin,DC=Fabrikam,DC=com)))

Cheers!
Swami

--
Swaminathan Pattabiraman [MSFT]
Developer – Active Directory Powershell Team

 

Comments

  • Anonymous
    April 14, 2009
    Why -like doesnt support "?" and [] elements as native -like operator in PowerShell? This is confusing. I'm think its possible to add that. Example 4: Get all users with an e-mail attribute       Get-ADUser -filter { email -like "" }In powershell we used to chech property avalability thys way:{email -ne $null}or just{email}Will this work in your filters? If not - can you please do it? It much easier and logical than checking -like ""In PowerShell "-not" operator can be replaced with "!". Are this possible here?I'm think that group category (security/distibution), group type (dl,g,u) and MemberOf should be parameters of respective cmdlets.Get-ADGroup -Cat SecurityGet-ADGroup adm -type globalGet-ADUser -memberof "Domain Admins"Such things will make your cmdlets not only "can do more" but also "can do more easily" :)Thanks!

  • Anonymous
    April 15, 2009
    In my previous post I discussed about the various features available in -Filter parameter aka “advanced

  • Anonymous
    April 20, 2009
    @Xaegr,Thanks for the feedback. Regarding Support for ? wildcard character:Internally, we convert the advanced filter to Ldap Filter and do server side filtering. Since, Ldap does not support wild card characters such as: ?, we are bound by that limitation.As a workaround one would have to do client side filtering using where-object cmdlet.Example:Get-ADUser -Filter { name -like "Adm*nistrator" } | Where {$_.Name -like "Adm?nistrator" }Cheers,Swami

  • Anonymous
    July 13, 2010
    Great! But how can i use negative -band? for example, how can i get Enabled computer accounts by such advanced filter like the purpose as below?get-adcomputer -f { !(userAccountControl -band 2) }

  • Anonymous
    January 22, 2011
    This will get you enabled computer accountsGet-ADComputer -Filter {enabled -eq "True" } | FT NAMEGet-ADUser -Properties * -Filter { enabled -eq "TRUE" } | FL name

  • Anonymous
    August 16, 2011
    Is there a way to supress the default set of attributes adn get only the ones you want and need?  I dont want to show SID, enabled, objectguid and just wan to show the ones I need.thanks in advance

  • Anonymous
    February 07, 2013
    Swaminathan,Thanks so much for this entry.  Your example 11 put an end to a very frustrating exercise.  Keep these entries coming!

  • Anonymous
    April 02, 2013
    hi, i need to export a list of all ADusers with this attributes values: employeeid, postofficebox and street.this is the ps command that i'm usiing:Get-ADUser -Filter * -properties employeeid | Export-Csv -Path c:loadfile.csv     it's works but only giveme employeeidhow to get more values on my list?thanks

  • Anonymous
    May 05, 2014
    I work in powershell to manage AD data and the one item I cannot find example of is how to compare attributes. To be clear, how to perform an 'ldapcompare' operation. Say an administrator wishes to compare that one attribute value is equal (or not equal, etc) to another attribute value such as  text or numerical comparison.Is there a way to do this, without using 'Where-Object' cmdlet? Using 'where-object' is costly as I must pull down all the data into my client before the pipeline hits 'where-object' for comparision, and that is not good on our medium size directory with all the users and data we have.Can this be done with a Get-ADUser filter so the comparision it is done server-side?Thanks

  • Anonymous
    July 06, 2014
    Nice blog ... Really helps meThanks

  • Anonymous
    October 14, 2015
    I have a list of user samAccountName and i want to iterate through the list using foreach and want to get the user detail from AD.So i have writen a code like this.. $users=get-content C:UsersniteshsScriptsusers_list.csv foreach ($user in $users) {   get-aduser -filter {samaccountname -like $user } } In the above mentioned code $user in the curly braces has not been evaluated..but when i am giving a string literal instead of $user... the code works...Can any one please guide me on that?

  • Anonymous
    December 26, 2015
     get-aduser -filter {samaccountname -like $user.sam } try this after making "sam" column header in you users file. $user.sam