Share via

Issue migrating a script to use managed identity

Joshua Sam 0 Reputation points
2023-09-03T21:23:26.1133333+00:00

Hi All,

Need your expertise help with an issue we are facing.

I am trying to migrate one of our PowerShell automation job to use system-managed identity.

Below is the script - Its basically supposed to delete all groups that a leaver is part of if they have been added to auto delete group within our tenant. I have attached screenshot of identity roles and error that we get. Any help would be appreciated.Error Screen

Identity roles

Connect-AzAccount -Identity

# Get the members of the Azure group

$Members = Get-AzADGroupMember -ObjectId xxxxxx-xxxxx-xxxxx-xxxxx

# For each member, get the groups they are in

Foreach ($member in $Members) { 

    # Get the groups that the member is a member of

    $Groups = Get-AzADUserMembership -ObjectId $member.objectid 

    # For each group, remove the member from the group, unless the group is the initial group

    foreach ($Group in $Groups) {

                        Remove-AzADGroupMember -ObjectId $Group.ObjectID -MemberId $member.objectid -erroraction Stop

                write-host "Removed $($member.displayname) from $($Group.displayname)"
    }
           
}
Microsoft Security | Microsoft Entra | Other

1 answer

Sort by: Most helpful
  1. Marilee Turscak-MSFT 37,396 Reputation points Microsoft Employee Moderator
    2023-09-06T00:09:10.9433333+00:00

    Hi @Joshua Sam ,

    Based on the script you shared it sounds like you are getting the "insufficient privileges to complete the operation" error when you run

    Get-AzADGroupMember
    

    In this case, it looks like you could be missing the permission to read groups.

    You may have granted your app permissions for the Microsoft Graph API, where the Get-AzADGroup uses the deprecated Azure AD Graph API. Try adding the service principal to the User Administrator role and make sure that the "Directory Reader" role is assigned under Azure AD > Roles and administrators > roles > add assignments > add the Object ID of the managed identity.

    See similar issue here: https://www.reddit.com/r/AZURE/comments/qrxvo9/addazadgroupmember_insufficient_privileges_to/

    Let me know if this helps and if you still face the issue.

    If the information helped you, please Accept the answer. This will help us as well as others in the community who may be researching similar information. Otherwise let me know if you have further questions.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.