Home > Mobile >  How to copy Azure AD Groups from an user to another user?
How to copy Azure AD Groups from an user to another user?

Time:08-11

I would like to know how to copy Azure AD Groups from an user to another. The script seems to work well but I can't code if ever the user is already a member of a particular group. Can you help me with the "Catch" part at the end of the script?

# Azure AD sign-in
Connect-AzureAD

# enter UPN of the first user
$user1 = Read-host "Enter username to copy from: "

# enter UPN of the second user
$user2  = Read-host "Enter username to copy to: " 

# Get ObjectId based on username of user to copy from and user to copy to
$user1Obj = Get-AzureADUser -ObjectID $user1
$user2Obj = Get-AzureADUser -ObjectID $user2


$membershipGroups = Get-AzureADUserMembership -All $true -ObjectId $user1Obj.ObjectId


foreach($group in $membershipGroups) {

    try
    {

Write-Host "[!] - Adding" $user2Obj.UserPrincipalName " to " $group.DisplayName "... " -ForegroundColor Yellow
Add-AzureADGroupMember -ObjectId $group.ObjectId -RefObjectId $user2Obj.ObjectId

    }
    catch
      {
        # User is already memberof $group.Displayname
    }

}

Write-Host "Done!"

CodePudding user response:

I am not familiar with Azure PowerShell cmdlets, so you will have to pardon me if I've made a mistake. This is based on just PowerShell logic:

# Azure AD sign-in
Connect-AzureAD

# enter UPN of the first user
$user1 = Read-host "Enter username to copy from: "

# enter UPN of the second user
$user2  = Read-host "Enter username to copy to: " 

# Get ObjectId based on username of user to copy from and user to copy to
$user1Obj = Get-AzureADUser -ObjectID $user1
$user2Obj = Get-AzureADUser -ObjectID $user2


$membershipGroups1 = Get-AzureADUserMembership -All $true -ObjectId $user1Obj.ObjectId
$membershipGroups2 = Get-AzureADUserMembership -All $true -ObjectId $user2Obj.ObjectId | Select-Object -ExpandProperty 'DisplayName'

foreach ($group in $membershipGroups) 
{
    if ($group.DisplayName -notin $membershipGroups2) { 
        Write-Host "[!] - Adding" $user2Obj.UserPrincipalName " to " $group.DisplayName '... ' -ForegroundColor Yellow
        Add-AzureADGroupMember -ObjectId $group.ObjectId -RefObjectId $user2Obj.ObjectId
    }
    else {
        Write-Host "User is already memberof $($group.Displayname)" -ForegroundColor 'Green'
    }
}
Write-Host "Done!"

Since Add-AzureADGroupMember doesn't produce an error if the user is already in the group, an alternate option would be to use an if statement, and a 2nd call to the 2nd user. This way you can compare a property such as the DisplayName to see if the user is already part of the group.

  • Related