Active Directory filtering

Hi, everyone. You probably know and use Get-ADUser and Get-ADComputer, both of them support Filter parameter that allows you to filter your query (for more information check out Get-Help about_ActiveDirectory_Filter).

However, there is one one gotcha if you want to filter on DistinguishedName attribute (and some others, more on it later). Turns out it supports only -eq operator literally and implicitly if you use –like operator, so these commands are equal:

  • Get-ADComputer –Filter 'DistinguishedName –like "CN=<…>"'
  • Get-ADComputer –Filter 'DistinguishedName –eq "CN=<…>"'

Strangely enough, you cannot use the wildcard character * with –like operator here, it just does not work:

PS C:\Users\username> Get-ADComputer -Filter 'DistinguishedName -like "*DC=com"'  
PS C:\Users\username>  

I came across this issue when I needed to enumerate machines in AD but exclude a certain OU. My intention was to use –notlike operator, but it did not work:
powershell No result!

Basically, there is no simple way here to follow the rule of thumb 'Filter Left, Format Right' which was introduced by Don Jones. Hence, if you face the same problem you have to pass unfiltered data through pipeline:

Get-ADComputer –Filter * | Where DistinguishedName –notlike *OU=*"  

There is also a nice article about AD filtering where it is explained why the wildcard character * does not work with certain attributes:

The wildcard character * is allowed, except when the AD Attribute is a DN attribute. Examples of DN attributes are distinguishedName, manager, directReports, member, and memberOf. If the attribute is DN, then only the equality operator is allowed and you must specify the full distinguished name for the value (or the * character for all objects with any value for the attribute).

Comments

comments powered by Disqus