Merge the members of the following Active Directory groups into a group called “RingCentral – Access.”
- RingCentral – Access 2
- RingCentral – Access 3
- RingCentral – Access 4
The group “RingCentral – Access” already exists and contains valid members. Each member is an Active Directory user object.
The Code
Get-ADGroup -Filter { name -like "RingCentral -*"} | Where-Object {$_.Name -ne "RingCentral - Access"} | Foreach-Object { Get-ADGroupMember $_ | Foreach-Object { Write-Host "User: $($_.SamAccountName)"; Add-ADGroupMember -Identity 'RingCentral -Access' -Members $_ -ErrorAction SilentlyContinue } }
In this statement, Active Directory groups containing the name “RingCentral – ” are queried that do not match the name “RingCentral – Access”. This is important because we do not care about the users in the group “Ring Central – Access”, just the groups “Ring Central – Access 2” and the related groups 3 and 4. The Active Directory users are queried in each of the these groups, and then the user is added to the main group “RingCentral – Access”.
This script produces and error for each user if they are already a member of the “RingCentral – Access” group. This was safely ignored and treated as informational.
Now comes the interesting part. We need to check to make sure the users are actually now in the primary “RingCentral – Access” group. To confirm, we need to query all of these users again, check their group membership, and make sure one of their groups is “Ring Central – Access.” If not, print some kind of error statement.
Get-ADGroup -Filter { name -like "RingCentral -*"} | Where-Object {$_.Name -ne "RingCentral - Access"} | Foreach-Object { Get-ADGroupMember $_ | Foreach-Object { if (-not ($_ | Get-ADPrincipalGroupMembership | Where-Object { $_.Name -like 'RingCentral - Access'})) { Write-Host "$($_.SamAccountName) not in 'RingCentral - Access'" } } }
Mission accomplished!