Search code examples
powershellactive-directoryldapldap-query

Combining LDAP Queries is not giving proper results


Good afternoon folks.

I am trying to run an LDAP query against a Domain Controller to include servers with the following requirements:

OperatingSystem=*server* (To include all Servers)

OR

OperatingSystem=*Enterprise* (To include Windows 10 Machines)

AND

userAccountControl:1.2.840.113556.1.4.803:=2 (Machine is NOT disabled)

If I run the following, I get what I need for servers:

Get-ADObject -searchbase "DC=DOMAIN,DC=LOCAL" -ldapfilter "(&(objectclass=computer)(operatingSystem=*server*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" | Sort-Object Name

If I run the following, I get what I need for the Windows 10 Enterprise Boxes:

Get-ADObject -searchbase "DC=DOMAIN,DC=LOCAL" -ldapfilter "(&(objectclass=computer)(operatingSystem=*Enterprise*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" | Sort-Object Name

However, if I combine like so, I get nothing:

Get-ADObject -searchbase "DC=DOMAIN,DC=LOCAL" -ldapfilter "(&(objectclass=computer)(operatingSystem=*server*)(|(operatingSystem=*Enterprise*))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" | Sort-Object Name

I have also tried this as well:

Get-ADObject -searchbase "DC=DOMAIN,DC=LOCAL" -ldapfilter "(&(objectclass=computer)(operatingSystem=*server*)(operatingSystem=*Enterprise*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" | Sort-Object Name

What am I possibly missing?


Solution

  • Your second to last filter is almost correct, to make it more readable:

    (&
      (objectclass=computer)
      (|
        (operatingSystem=*server*)
      )
      (operatingSystem=*Enterprise*)  # <- this one should be inside the OR clause
      (!(userAccountControl:1.2.840.113556.1.4.803:=2))
    )
    

    So, the filter should be:

    (&(objectclass=computer)(|(operatingSystem=*server*)(operatingSystem=*Enterprise*))(!userAccountControl:1.2.840.113556.1.4.803:=2))
    

    As you can note, (!(userAccountControl:1.2.840.113556.1.4.803:=2)) can also be simplified to (!userAccountControl:1.2.840.113556.1.4.803:=2). And, if you use Get-ADComputer instead of Get-ADObject, you can get rid of the (objectclass=computer) clause.