Recently I had a request to copy group membership from multiple groups into one single group.  This was because the application they were using did not support group nesting, it would only support granting permissions to a single Active Directory group.

I came up with the script below.

#This script will list all members from each of the source groups and add them to the destination groups.
Clear-Host
$sourcegroups = @(‘sourcegroup1′,’sourcegroup2′,’sourcegroup3′)
$destinationgroup = ‘destinationgroup’
$credential = Get-Credential
$dc = Get-ADDomainController | Select-Object hostname
foreach ($sourcegroup in $sourcegroups) {
    try {
        $ErrorActionPreference = ‘Stop’
        $newMembers = Get-ADGroupMember $sourcegroup -Server $dc.hostname
        }
    catch {
        Write-Host “Error: $($_.Exception.Message)”
        }
foreach ($member in $newMembers) {
        try {
            $ErrorActionPreference = ‘Stop’
            Add-ADGroupMember -Identity $destinationgroup -Members $member -Server $dc.hostname -Credential $credential
            #REM below line if you do not want all successful group member adds to display to the screen.
            write-host “$member from $sourcegroup added to $destinationgroup”
        }
        catch {
                #Write-Host “$member from $sourcegroup already exists in $destinationgroup”
                Write-Host “Error on account $member from $sourcegroup : $($_.Exception.Message)”
              }
        }
        }
#Clean Up Variables
$clearvars = @(“sourcegroup”, “destinationgroup”, “credential”, “dc”, “sourcegroups”, “member”, “newmembers”)
foreach ($var in $clearvars) {
        Clear-Variable -Name $var
    }
Clear-Variable -Name var
Clear-Variable -Name clearvars