Short one today, the script below will import a CSV from C:\temp\users.csv that contains a ‘User Name’ field and will locate all Active Directory users that match that. Where multiple matches are found it will populate the exported CSV with all matches.
The Script
# VARIABLES
$CSVPath = "C:\temp\users.csv"
$Exportpath = "C:\temp\report.csv"
$csv = import-csv $CSVPath
# Search for AD users with given first and last name
$result = @()
foreach($row in $csv) {
# Work out the first and last name values
$nameValue = $row."User Name"
$firstName = $row."User Name".Substring(0, $row."User Name".IndexOf(" "))
$lastName = $nameValue.replace($firstName, "").Trim()
# Get a user using first and last name
$user = Get-ADUser -Filter {GivenName -eq $firstname -and sn -eq $lastname}
# Add a custom object to $result
$result += [PSCustomobject]@{
'User Name' = $row."User Name"
SamAccountName = $user.SamAccountName -join ', '
}
}
# Remove an existing file if exists then export csv
if(Test-Path -path $Exportpath) {
Remove-item $Exportpath -Verbose
}
$result | export-csv -path $Exportpath -NoClobber -NoTypeInformation -Force