This PowerShell Script sample shows how to get a list of active directory Sam Account name based on display name.
This PowerShell Script sample shows how to get a list of active directory Sam Account name based on display name.
Step1: Run the script in the Windows PowerShell Console, type the one command: Import-Module <Script Path> at the prompt.
For example, type Import-Module C:\Script\GetADUserInfo.psm1
This is shown in the following figure.
Step 2: You can type the command Get-Help Get-OSCSamAccountName –Full
to display the entire help file for this function, such as the syntax, parameters, or examples.
Example 1: Type Get-OSCSamAccountName -CsvFilePath C:\Script\Users.csv
command in the Windows PowerShell Console.

This command will list all active directory users Sam Account Name info.
Note
The import csv file format must follow the following format.

Here are some code snippets for your references.
Foreach($Name in $Names)
{
$Name = $Name.Replace(" ","") -split ","
$FirstName = $Name[0].Trim()
$LastName = $Name[1].Trim()
$UserName = $FirstName + " " + $LastName
#Retrieve the ad users based on previous two variables.
$SamAccountName = Get-ADUser -Filter{ Surname -eq $LastName -and GivenName -eq $FirstName}|`
Select -ExpandProperty SamAccountName
If($SamAccountName -eq $null)
{
$SamAccountName = "NotFound"
}
#Output the result
New-Object -TypeName PSObject -Property @{DisplayName = $UserName
SamAccountName = $SamAccountName
}
}
Foreach($Name in $Names) { $Name = $Name.Replace(" ","") -split "," $FirstName = $Name[0].Trim() $LastName = $Name[1].Trim() $UserName = $FirstName + " " + $LastName #Retrieve the ad users based on previous two variables. $SamAccountName = Get-ADUser -Filter{ Surname -eq $LastName -and GivenName -eq $FirstName}|` Select -ExpandProperty SamAccountName If($SamAccountName -eq $null) { $SamAccountName = "NotFound"} #Output the result New-Object -TypeName PSObject -Property @{DisplayName = $UserName SamAccountName = $SamAccountName }}
Windows PowerShell 2.0
Windows Server 2008 R2 or higher version