Powershell – Getting AD username from first name and surname in CSV file

active-directorypowershell

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!

Best 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 }
}