Script to pull sAMAccountName from display names

Hey All,

What’s the best way to pull list of sAMAccountNames from a AD domain email format like


I have a bunch of users in a user provided .CSV that I need to find out the sAMAccountNames.



Does that consistently match either userprincipalname or mail?

There’s a UPN column which has the email listed like a above.

Assuming the column name in your CSV is email, this is one way.

$csvfile = 'some\path\to\csvfile.csv'

Import-Csv $csvfile | foreach {
    Get-Aduser -Filter "userprincipalname -eq '$($'" | Select SamAccountName

I had the same question i the past, where I got help for this too :slight_smile:
For me this works very well.

I use it in a for each loop:

param (
    $ImportPadEnBestand = '\\xxxxxx -delimiter ";",
    $ExportPadEnBestand = '\\xxxxxx' 

$Names = Import-Csv $ImportPadEnBestand -Encoding UTF7
Write-Host "Nr of records $($ImportPadEnBestand): $($Names.Count)"

Start Clean
Remove-Item $ExportPadEnBestand -Confirm: $true -ErrorAction SilentlyContinue

# If export exist the do not execute the script 
if ( Test-Path $ExportPadEnBestand ) {

# Just check youreself
$Found     = 0
$Notfound = 0

foreach ($Name in $Names.displayname) {

    #Write-Progress -activity "$($name.DisplayName)"
    #sleep 1
    if ( Get-ADUser -Filter {DisplayName -like $Name} ) {
        Get-ADUser -Filter {DisplayName -like $Name} | select SamAccountName | Export-Csv $ExportPadEnBestand -Append
    else {
        Write-Host "Notfound: $name"

Write-Host "Find     : $TFound"
Write-Host "Cannot find: $TellerNietGevonden"