Powershell script to find AD user with firstname and lastname

active-directorypowershell

I wrote a script to find users in AD using their firstname and lastname from a csv file.
When i execute the script, I dont get any output. Also no error…. Please help if any issues with the script.

Import-module ActiveDirectory
$users = Import-Csv -Path 'C:\Users\smishra\Desktop\list.csv'
$aduser = foreach ($user in $users)
{
$firstname = "$user.first"
$lastname = "$user.last"
Get-ADUser -Filter {GivenName -like $firstname -and Surname -like $lastname} -properties EmailAddress | select UserPrincipalName, EmailAddress
}
$aduser | Export-Csv user.csv -NoTypeInformation

Best Answer

Made a few of changes. 1. Declaration of Variables, removed quotes. 2. Get-AdUser command, changed "surname" to "SN". 3. Declared an array to contain the complete report with incremental addition.

Import-module ActiveDirectory 
$users = Import-Csv -Path 'file.csv' 
$CompleteReport=@()
foreach ($user in $users) {
    $firstname = $user.first
    $lastname = $user.last
    $aduser = Get-ADUser -Filter 'GivenName -eq $firstname -and sn -eq $lastname' -properties EmailAddress | select UserPrincipalName, EmailAddress
    $CompleteReport = $CompleteReport+$aduser
} 
$CompleteReport | Export-Csv user.csv -NoTypeInformation