FIX: Get-AzureADGroupMember: Error occurred while executing AddGroupMember

Message: One or more added object references already exist for the following modified properties: ‘members’.

This is very specific, but I received the error message below after I tried to add users to an AzureAD group, after I first emptied the group.

Add-AzureADGroupMember : Error occurred while executing AddGroupMember 
Code: Request_BadRequest
Message: One or more added object references already exist for the following modified properties: 'members'.
RequestId: c257ce87-68f6-4d08-8bb3-4c54c7d25d8f
DateTimeStamp: Mon, 20 May 2019 10:26:17 GMT
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed

Do you recognize this?
Then this blog post will help you.

Let’s “Fix” this then?

It sounds a bit too specific, but I’m sure more Azure Engineers are experiencing this problem.

In my script I first remove all users (Devices) from an AzureAD Group, and then I retrieve all managed users (Devices) and add them again to the AzureAD Group.

$AddToGroup = "Group"
$RegisteredOwnerUpn = "EMAIL"  
$group = Get-AzureADGroup -SearchString "$($AddToGroup)" -ErrorAction Stop
$AllDEMDevices = (Get-MsolDevice -RegisteredOwnerUpn $RegisteredOwnerUpn)

foreach ($CurrentMember in $(Get-AzureADGroupMember -ObjectId $($group.ObjectId)))
    Remove-AzureADGroupMember -ObjectId $($group.ObjectId) -MemberId $($CurrentMember.ObjectId)

foreach ($DEMDevice in $AllDEMDevices)
    Add-AzureADGroupMember -ObjectId $($group.ObjectId) -RefObjectId $DEMDevice.ObjectId.Guid

Only when I added the last user every time I got an error message that it was already in the group. Strange, because I completely empty the group?

After a while (I don’t dare to admit how long) I found out my mistake.

I looked at for Get-AzureADGroupMember and I immediately noticed that -All is there.

Apparently Get-AzureADGroupMember has a maximum of 100 results. Because of this my last user was not retrieved, nor removed from the group.

And yes, that really is the solution:

Get-AzureADGroupMember -ObjectId $($group.ObjectId) -All $true

A little extra

This post contains PowerShell. Would you like to learn the basics better? I have created a new website to learn basic PowerShell in an ’emulator’ environment.
Click here to go learn Basic PowerShell.

Published by

Bas Wijdenes

My name is Bas Wijdenes and I work as a PowerShell Automation Engineer @ Wortell.

Leave a Reply

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