Pages

Monday, July 6, 2015

Add list of users (by Display Name) to AD group from .csv file

This script will use a .csv file containing a list of users that need to be made members of an AD group. In this scenario only the display names are known, not the usernames.
The first cell in the column containing the user display names must use the value “Name”.

$ListOfUsers = Import-csv -Path <INSERT PATH TO .CSV FILE>
$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
}
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 "<INSERT GROUP NAME>"
    Add-ADGroupMember -Identity $GroupToAddTo -Member $ItemDetails.DistinguishedName
    $ItemDetails = $NULL
    }
}
}

No comments:

Post a Comment