# Getting AD username from first name and surname in CSV file

I have a CSV file with a list of users' first and last names, with column headers as Firstname and Surname. I'm trying to extract these users' usernames from the directory by importing the CSV file using Import-CSV, then using Get-ADUser.

Here is what I have so far:

$names = Import-CSV C:\path\to.csv ForEach ($Name in $Names) { Get-ADUser -Filter { GivenName -like "$Name.Firstname" } }


This returns no results, but no errors either.

Ultimately, the command should compare both first name and surname, but as I can't get it to work with one field I thought it best not to complicate it by trying to compare two!

-
Just like to point out that this won't necessarily give you accurate results, depending on the number of users you have, and the variety of first,last combinations. That is, a given first,last combination won't necessarily be unique with the absence of a qualifying value (e.g.: middle initial). Cheers. –  Simon Catlin Sep 16 '13 at 17:04
@SimonCatlin I had thought that it would: running something like Get-ADUser -Filter { GivenName -like "John" } does return all of the users whose first name is John... unless I'm missing something? –  toryan Sep 16 '13 at 18:05

## 1 Answer

Add as the first line of your CSV file a row containing the column headers for your file. You then use those headers as the property names when iterating through the file.

So your file should look something like:

Firstname,Lastname
Joe,Schmoe
John,Doe
Jane,Doe


Then your code should work as is.

Also, the filter seems not to like $Name.lastname. I'm not sure exactly why, but even property expansion is not doing the trick. If you collapse this into a single string variable it work: $names = Import-CSV C:\path\to.csv
ForEach ($Name in$Names)
{
$nameFilter =$Name.Firstname
Get-ADUser -Filter { GivenName -like \$nameFilter }
}

-
The CSV file has column headers. They are 'Firstname' and 'Surname'. I should mention that the final command should compare both first name and surname, but given that searching for one field doesn't work it seems ambitious to try and search for two at this point! –  toryan Sep 16 '13 at 18:02
@toryan It should work using the code from my edit. –  squillman Sep 16 '13 at 18:35
This worked, thanks! –  toryan Sep 17 '13 at 9:56