Ambiguous Fuzzy search in AD


Working in big AD forests and domains can be sometimes challenging, as powershell cmdlets require you perfect identity matches. In an AD of a global corporation, where you have tons of John, Sam, Doe, Smith, Martin, Schmidt , finding that information may be time consuming: is the name given a first name, a last name, a maiden’s name… You have to do Ambiguous Fuzzy search in AD.

Instead of being embarassed asking Here’s a little snippet that takes as input

  • a user name
  • a switch

If the switch ‘strict’ is not present,

  • An AD search will be created to find the best match against first names, last names, SAM Account names. In fact it does ambiguous name resolution.
  • If only one account is found, the operation is processed
  • If multiple account are found, an error is thrown showing which account are matching your criteria, so you can be more precise when relaunching your cmdlet

If the switch ‘strixt’ is present, the user name must be a unique perfect matching identity as the parameter will be used as a parameter to Get-ADUser

<pre class="lang:default decode:true" title="AD ambiguous search"># AD search ambiguous

Function Do-ADUserSomething {
[switch] $strict
 if ($strict) {
   $u = Get-ADUser -Identity $user
} else {
 $u = Get-ADUser -LDAPFilter "(anr=$user)"
 if ($u) {
   if ($u -is [array]) 
     throw "Found multiple users matching (anr=$user): $($u.samAccountName -join ', ' )"
   #TO DO: Add your code using $u 
  throw "No user found matching criteria (anr=$user)"


You just need to fill in the #TO DO line with your adhoc code.

You may want to use return values or another mechanism like return values or warning instead of throwing up an exception in case there is more than one user which matches your criteria. You can also replace GEt-ADUser with a more generic Get-ADObject cmdlet if your work include contacts or groups.