PowerShell – Find Active Directory Users by First and Last Name

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

$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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.