简体   繁体   中英

Optimal way of finding a user in AD (Get-ADUser) based on different input

I'm looking for your thoughts on the optimal way of doing this.

The goal is simply to find a given user based on different possible inputs.

The possibilities are:

$input = "John,Smith"
$input = "John Smith"
$input = "John Smith(ext)"
$input = "Smith,John"
$input = "Smith John"
$input = "Smith John(ext)"

My working solution is :

if ($input -like "*(*" ) {
$input = $input -replace '\([^\)]+\)'
}

if ($input -like "*,*"){
$FullName = $input -split "," 
} 
elseif ($input -like "* *"){
$FullName = $input -split " "
} 


get-ADUser -Filter " ( ( (GivenName -like '$($FullName[0])*') -and (SurName -like '$($FullName[1])*') ) -or ( (SurName -like '$($FullName[0])*') -and (GivenName -like '$($FullName[1])*') ) ) "

So basically what is going on is :

-If the input contains parenthesis, remove them and what is between them.
-If the input contains a comma, split the string on that.
-If the input contains a space, split the string on that.
-Get-AdUser, filtering (GivenName and Surname) OR (Surname and GivenName)
since I don't know which order they will be in.

It works fine as is but i'm always curious of finding the optimal way.

Do you have anything to suggest in this scenario? Thanks a lot for your input.

Use -LDAPFilter and Ambiguous Name Resolution ( anr ):

Get-ADUser -LDAPFilter "(anr=John Doe)"
Get-ADUser -LDAPFilter "(anr=Doe John)"

Just replace the comma with a space, and remove "(ext)" . Variable name $input is reserved, so it shouldn't be used:

$name = $name -replace ",", " "
$name = $name -replace "\(ext\)", ""

Or chaining the -replace operator:

$name = $name -replace ",", " " -replace "\(ext\)", ""

The search would be:

Get-ADUser -LDAPFilter "(anr=$name)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM