Import a CSV File of Names and Lookup User Details in AD with Powershell

The is a very useful script especially if you are like me and receive requests where you need to provide certain information on specific users in Active Directory. The information you are given to start with might be limited, in this example I had the users first and last names.

Without the use of Powershell you would have to lookup each user manually to obtain the information you need, on a list of 100 users this could take some time. So with the help of powershell we can have this information within a matter of minutes. In this example we are going to import a list of names and then retrieve their email address to send them a specific email.

The first thing we need to do is add the list of names to a CSV file, I have put their first and last-name in the same column (column A). As we have only used one column, in the below example of code I have used Get-Content as opposed to Import-CSV. You can replace Get-Content with Import-CSV and the code will still work. (The next guide will show you how to deal with data in multiple columns)

Import Users and Retrieve their Email Address

$csvfile = Get-Content -Path H:\names.csv 
foreach($user in $csvfile) { 
    try { 
        #look up users email 
        $aduser = (Get-ADUser -filter {DisplayName -eq $user} -Properties Mail).Mail 
        Write-Output "$aduser" 
        } catch {              
            write-output $_.exception.message 
        } 
} 

Just for ease I have pasted the same code below but with Import-CSV

$csvfile = Import-CSV -Path H:\names.csv 
foreach($user in $csvfile) { 
    try { 
        #look up users email 
        $aduser = (Get-ADUser -filter {DisplayName -eq $user} -Properties Mail).Mail 
        Write-Output "$aduser" 
        } catch {              
            write-output $_.exception.message 
        } 
} 

Leave a Reply

Your email address will not be published. Required fields are marked *