Adding a M365 User to Multiple Groups Using Graph PowerShell

Managing group memberships in Microsoft 365 can be a common and time-consuming task for administrators. Using PowerShell and Microsoft Graph, you can simplify and automate the process of adding users to multiple groups in bulk. Below, we provide a PowerShell script that demonstrates how to achieve this efficiently.

The Script


# Install the Microsoft Graph PowerShell module if not already installed
# Install-Module -Name Microsoft.Graph -Scope CurrentUser

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Group.ReadWrite.All", "User.ReadWrite.All"

# Define the user's UPN (User Principal Name) and the group IDs
$userUPN = "jacobdoe@7xh7fj.onmicrosoft.com"
$groupIds = @(
    "1cbe8c31-589d-453a-a1e5-045f7f00c967",
    "4a6c54df-9235-4854-8b98-5c0045c02855",
    "d2449eb1-db4a-4d87-83dd-988f7af420b1"
    # Add more group IDs as needed
)

# Get the user object
$user = Get-MgUser -UserId $userUPN

# Function to add a user to a group
function Add-UserToGroup {
    param (
        [string]$userId,
        [string]$groupId
    )
    try {
        New-MgGroupMember -GroupId $groupId -DirectoryObjectId $userId
        Write-Host "Successfully added user to group with ID: $groupId" -ForegroundColor Green
    } catch {
        Write-Host "Failed to add user to group with ID: $groupId. Error: $_" -ForegroundColor Red
    }
}

# Loop through each group ID and add the user to the group
foreach ($groupId in $groupIds) {
    Add-UserToGroup -userId $user.Id -groupId $groupId
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph

Write-Host "User has been added to all specified groups." -ForegroundColor Green
                            

Script Output

How the Script Works

  • Connect to Microsoft Graph: The script starts by connecting to Microsoft Graph using the Connect-MgGraph cmdlet. Ensure that the required permissions Group.ReadWrite.All and User.ReadWrite.All are granted.
  • Define User and Groups: Specify the User Principal Name (UPN) of the user to be added to groups. List the Group IDs in the $groupIds array.
  • Retrieve the User Object: The script fetches the user's details using the Get-MgUser cmdlet.
  • Add the User to Groups: A custom function Add-UserToGroup is defined to handle the addition of the user to a group. Inside a loop, the script iterates through each group ID in $groupIds and invokes the function.
  • Error Handling: If an error occurs during the group addition process, it is caught and displayed in red text, ensuring transparency about failures.
  • Disconnect: After all groups are processed, the script disconnects from Microsoft Graph using Disconnect-MgGraph.

Possible Errors & Solutions

Error Cause Solution
Insufficient Permissions Missing API permissions for Microsoft Graph. Ensure the account has Group.ReadWrite.All and User.ReadWrite.All permissions in Azure.
Cannot find the user Incorrect User Principal Name or the user does not exist. Verify the $userUPN value and ensure the user exists.
Cannot add a member to a group The group is not a Microsoft 365 group, or the user is already a member. Confirm the group IDs in $groupIds are valid.
Rate Limiting or Timeout Too many requests in a short period. Introduce a delay between API calls using Start-Sleep.

Conclusion

This PowerShell script streamlines the process of adding a user to multiple Microsoft 365 groups. It is versatile, with robust error handling, and can be easily modified to fit your organization's needs. By leveraging the Microsoft Graph PowerShell module, administrators can significantly reduce the time and effort required for managing group memberships.

Feel free to customize and expand this script to handle bulk operations or integrate it with other automation workflows!

© m365corner.com. All Rights Reserved. Design by HTML Codex