How can I pull usernames from AD using powershell and the email addresses

1.4k Views Asked by At

I can pull a single username from AD by searching for the email address, but I would like to pull multiple email addresses from the CSV and log them in an output file. I know I need to broaden the search here: mail -eq '[email protected]' with something such as -like or a variable but I'm having difficulty finding a solution.

Code:

$InputFile = 'C:\emailaddresses.csv'
$Outputfile = 'C:\usernames.csv'

Import-CSV -Path $InputFile 
      | ForEach-Object { Get-ADUser -Filter { mail -eq '[email protected]' } | select SamAccountName } 
      | Export-Csv $OutputFile -NoTypeInformation
1

There are 1 best solutions below

0
dcaz On

the answer is probably spacing and AD calls are a pain note the $Email

$InputFile = 'C:\emailaddresses.csv'
#assumption that header for the file above is email
$Outputfile = 'C:\usernames.csv'

Import-CSV -Path $InputFile | ForEach-Object { 
    $email = $null
    $email = $_.email
    Get-ADUser -Filter { mail -eq $email } | Select-Object SamAccountName } | Export-Csv $OutputFile -NoTypeInformation

I assume the header is email in the first csv and I am not sure if you want -eq or -like but my answer here will get you there.

I tested this on my machine and it works.