PowerShell AD LDS query with filter using wildcard not behaving as expected
You cannot use a partial wildcard in an LDAP filter on a DN attribute such as distinguishedName
.
From Active Directory: LDAP Syntax Filters
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).
Your first example distinguishedName -like "*"
means "distinguishedName is not empty" which is why it returns results.
Instead use Where-Object
to match on attributes outside of the LDAP filter syntax. The following returns all AD objects from $server
under $searchBase
then uses Where-Object
to filter the collection where distinguishedName
matches CN=Jason*
.
Get-ADObject -Server $server -SearchBase $searchBase -Filter * |
Where-Object { $_.distinguishedName -like 'CN=Jason*' }
You also have a full regex option using -match
instead of -like
.
MasterOfNone
I was hired as a database administrator at a seminary in July 2013. I am am MCP in Querying SQL Server 2012 and one exam away from my MCSA.
Updated on September 18, 2022Comments
-
MasterOfNone almost 2 years
I am the administrator for a learning management system website that stores its page structure in AD LDS. I am trying to run a query to get objects (pages on the site) matching a filter for distinguishedName. My filter is not behaving as expected.
Below are three queries, all of which are identical except for the filter parameter. This isn't exactly what I am trying to do, but for demonstration purposes this will illustrate my problem.
This works (returning a very large number of results):
Get-ADObject -Server 'localhost:389' -SearchBase 'CN=Academics,CN=Portal,O=Jenzabar,C=US' -Filter 'distinguishedName -like "*"'
This also works, (returning a single result):
Get-ADObject -Server 'localhost:389' -SearchBase 'CN=Academics,CN=Portal,O=Jenzabar,C=US' -Filter 'distinguishedName -like "CN=LEC,CN=Academics,CN=Portal,O=Jenzabar,C=US"'
However, this returns no results, and I do not understand why:
Get-ADObject -Server 'localhost:389' -SearchBase 'CN=Academics,CN=Portal,O=Jenzabar,C=US' -Filter 'distinguishedName -like "C*"'
As far as I can tell, the third query should return all results from the first query, and it should at least certainly return the single result from the second query. Any help would be appreciated!
-
MasterOfNone almost 9 yearsThank you. I understand this answer and it solves my problem. I appreciate the clear explanation!