Drake
Drake

Reputation: 11

How can I use PowerShell to translate a full name to samaccountname without middle initial?

What I have now is a PS script that parses through a text file. The text file is structured like this:

John Smith
Anna Jones
John Brown

The problem is, the Display Name in AD is something like this:

John C. Smith
Anna G. Jones
John A. Brown

And I don't know the middle initials. I've pasted the script I have. It will give me the correct samaccountname if I include the middle initial in the text file. But again, I don't know the middle initials of all these users. Is there a way to get the samaccountname if I don't know the middle initial? Maybe pass a wildcard into the query?

$users = Get-Content C:\Temp\UserList.txt

foreach ($user in $users){
Get-ADUser -Filter "Name -like '$user'" | Select-Object samaccountname
}

Upvotes: 0

Views: 772

Answers (1)

Anthony Stringer
Anthony Stringer

Reputation: 2001

something like this may work

$users = Get-Content C:\Temp\UserList.txt

foreach ($user in $users) {
    $split = $user.split()
    $first = $split[0]
    $last = $split[-1]
    Get-ADUser -Filter "Name -like '$first*$last'" | Select-Object samaccountname
}

Upvotes: 1

Related Questions