简体   繁体   中英

Get-ADUser -filter parsing

I am running a script which takes a person's first and last name from an SAP extract, and reads AD to get their UPN. For most people, this works; however there are a bunch of users whose first name is an issue. For instance "Philip Davies" (names changed to protect the innocent) in SAP is "Phil Davies" in AD. So: I have used the following command and it works:

Code:

Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -eq "Phil" -and Surname -eq "Davies"}

I then realised I can check for the first three characters which will NORMALLY be the same in the contracted name... so I did this which also works:

Code:

Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -like "Phi*" -and Surname -eq "Davies"}

Next step: variables; so I try this and it works:

Code:

$fna="Phil"
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -eq $fna -and Surname -eq "Davies"}

But if I try this:

Code:

$fna="Philip"
$fna=$fna.Substring(0,3)
Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -like $fna* -and Surname -eq "Davies"}

I get no result. It doesn't matter if I use brackets, double-quotes, single-quotes, anything. As soon as I try to parse a variable AND use a wildcard, it either produces an error message or no result.

Can anyone please help me with this either by using the "-ldapfilter" method or telling me how to parse AND wildcard?

Thanks

You should not use the wildcard with a variable since you wish to check it with a name which is a string. So what you can do is directly wrap the string with the wildcard and store the final thing in a variable like:

$fna="Philip"
$fna="$($fna.Substring(0,3))*"

Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -Filter {GivenName -like $fna -and Surname -eq "Davies"}

or you can use the LDAP Filter directly like :

Get-ADUser -SearchBase "OU=CBC Users,DC=cbc,DC=int" -LDAPFilter "(&(GivenName=$fna)(Sn=Davies))"

Hope it helps.

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