Copy Azure Security Group Members

By | November 16, 2022

Duplicate all members of one security group into another (unless they already exist)

I needed to do this for reasons and got very bored of instructing people how to do it through the GUI outputting the members of one group then bulk importing them to the next so scripted it.

I actually prefer the export and import method for one-off operations as it means you have a csv list showing exactly what you did and can see the results for each item in the log but when there’s a lot of lists to do or you need to do it regularly scripting makes sense, I did make this one output a lot of real time activity however.

You just need to populate the variables $oldgroupname and $newgroupname with display names of the source and target group. Both need to pre-exist, it wont create the new group for you.

# connect-AzureAD

$oldgroupname =  "Old Security Group Name"
$newgroupname = "New Security Group Name"

$oldgroup = Get-AzureADGroup -SearchString $oldgroupname
$oldmembers = $oldgroup | Get-AzureADGroupMember

Write-Host "Found " -ForegroundColor Green -NoNewline
Write-Host $oldmembers.count  -ForegroundColor Red -NoNewline
Write-Host " users in group "  -ForegroundColor Green -NoNewline
Write-Host $oldgroup.DisplayName  -ForegroundColor White

$newgroup = Get-AzureADGroup -SearchString $newgroupname
$newmembers = $newgroup | Get-AzureADGroupMember

Write-Host "Adding members to new group " -ForegroundColor Green -NoNewline
Write-Host $newgroup.DisplayName  -ForegroundColor White
$i=0
ForEach ($member in $oldmembers) {
    $i++
    If ($member -notin $newmembers) {
        Write-Host "Member " -ForegroundColor Green -NoNewline
        Write-Host $i -ForegroundColor Red -NoNewline
        Write-Host " of " -ForegroundColor Green -NoNewline
        Write-Host $oldmembers.Count -ForegroundColor Red -NoNewline
        Write-Host " - " -ForegroundColor Green -NoNewline
        Write-Host $member.UserPrincipalName -ForegroundColor Cyan -NoNewline
        Write-Host " - Not Currently in group - Adding"  -ForegroundColor Green
        Add-AzureADGroupMember -ObjectId $newgroup.ObjectId -RefObjectId $member.ObjectId
    }
    Else {

        Write-Host "Member " -ForegroundColor Green -NoNewline
        Write-Host $i -ForegroundColor Red -NoNewline
        Write-Host " of " -ForegroundColor Green -NoNewline
        Write-Host $oldmembers.Count -ForegroundColor Red -NoNewline
        Write-Host " - " -ForegroundColor Green -NoNewline
        Write-Host $member.UserPrincipalName -ForegroundColor Cyan -NoNewline
        Write-Host " - Currently in group - No Action"  -ForegroundColor Red
    }

}

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *