Reputation: 2064
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.
Upvotes: 1
Views: 253
Reputation: 1660
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)"
Upvotes: 3