Use Powershell to Create and Add members to Active Directory Groups from csv

This is a task that I feel like there are a ton of ways to do it, this is just mine. With this you create a csv file with two columns; the first is the username of the person you want to add to the group and the second is the group that the person should be in. The script will check to see if the group exists and if it doesn’t it will be created in the path you define and then it will add the member, if the group does already exists it simply adds the user. This is a fast way to create a bunch of groups if you need to. For connecting to Active directory see this post.

Script:

#You need to have a connection to AD first or run this from a DC (see https://allthesystems.com/2020/08/powershell-connection-examples/)
#Define path to csv and basepath to create groups if they dont exist
$list = Import-Csv -Path C:\Path\to\csv\newgroups.csv
$BasePathForGroups = "OU=Path,OU=To,OU=OU,DC=Domain,DC=com"

foreach ($item in $list) {
    #Set variables for loop from csv line
    $group = $item.group
    $member = $item.member

    #Check if group exists
    if(Get-ADGroup $group){

        Write-Host "group exists. adding member: $member"
        #Adds member
        Add-ADGroupMember -Identity $group -Members $member

    }
    else {
        Write-Host "Group doesnt exist.  creating: $group"
        #Creates group
        New-ADGroup -Name $group -SamAccountName $group -GroupCategory Security -GroupScope Global -DisplayName $group -Path $BasePathForGroups
        #Adds member
        Add-ADGroupMember -Identity $group -Members $member 
    }

}
Tagged : / /