Share via

Bulk adding/removing users from multiple O365 groups

Alex Hannah 1 Reputation point
2020-08-26T11:37:10.417+00:00

Hi all,

I'm trying to find two PowerShell scripts to achieve the following:

  1. Remove all Owners & Members from a defined list of multiple O365 groups.
  2. Add 2 users as Owners for the same defined list of multiple O365 groups.

All of the information I've found online seems to point towards removing a single user from all groups and not a defined selection.

I hope you can assist me with this requirement, please let me know if you need any further information.

Many thanks,

Alex.

Microsoft Security | Microsoft Entra | Microsoft Entra ID
0 comments No comments

1 answer

Sort by: Most helpful
  1. Alfredo Revilla - Upwork Top Talent | IAM SWE SWA 27,546 Reputation points Moderator
    2020-08-26T17:36:08.313+00:00
    function RemoveAllOwnerAndMembers {
        param(
            [Parameter(Mandatory)]
            [Guid[]]$GroupIds
        )
    
        foreach ($Id in $GroupIds) {
            $Owners = Get-AzureADGroupOwner -ObjectId $Id
            foreach ($Owner in $Owners) {
                Remove-AzureADGroupOwner -ObjectId $Id -OwnerId $Owner.ObjectId
            }
            $Members = Get-AzureADGroupMember -ObjectId $Id
            foreach ($Member in $Members) {
                Remove-AzureADGroupMember -ObjectId $Id -MemberId $Member.ObjectId    
            }
        }
    }
    
    function AddNewOwners {
        param(
            [Parameter(Mandatory)]
            [Guid[]]$GroupIds,
            [Parameter(Mandatory)]
            [Guid[]]$NewOwnersIds
        )
    
        foreach ($Id in $GroupsIds) {
            foreach ($NewOwnerId in $NewOwnersIds) {
                Add-AzureADGroupOwner -ObjectId $Id -RefObjectId $NewOwnerId
            }
        }
    }
    
    Connect-AzureAD
    
    # Replace values
    RemoveAllOwnerAndMembers -GroupIds <guid_or_string_array>
    AddNewOwners -GroupIds <guid_or_string_array> -NewOwnersIds <guid_or_string_array>
    

    Please let us know if this answer was helpful to you. If so, please remember to mark it as the answer so that others in the community with similar questions can more easily find a solution.

    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.