Powershell – Add AD User to Group Using Distinguished Name

A colleague of mine had to add a bunch of people to an AD group, but all they had was the names of the people. A couple of problems with that…

1. The name may be wrong

2.There may be more than one account with the same Distinguished Name.

This script accounts for that and will only add the user to the group if the name matches and there is only 1 user with the same name

The CSV file has just on column with a header called Name

$ListOfUsers = Import-csv -Path c:\temp\names.csv
$ItemDetails = $NULL

foreach ($item in $ListOfUsers)
{
$a = $item.name
$ItemDetails = get-aduser -Filter {DisplayName -eq $a} -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if (($ItemDetails.count) -gt 1)
{
 Write-Host "Too many accounts with DisplayName $a" -ForegroundColor Yellow 
 $ItemDetails = $NULL
}
else
{
    
if ($ItemDetails -eq $NULL)
    {
    Write-Host $a "does not exist in AD"  -ForegroundColor Red
    $ItemDetails = $NULL
    }
else
    {
    Write-Host $a  "does exist in AD" -ForegroundColor Green
    $ItemDetails.DistinguishedName
    $GroupToAddTo = get-adgroup -Identity "Your Test Group" 
    Add-ADGroupMember -Identity $GroupToAddTo -Member $ItemDetails.DistinguishedName 
    $ItemDetails = $NULL
    }
} 
}

 

Leave a comment

Your email address will not be published.

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