Manage Microsoft Team Members With Graph PowerShell

Adding members to a Microsoft Team can be a routine but critical task, especially for organizations that need to manage dynamic teams efficiently. This PowerShell script provides a streamlined, interactive console-based approach to adding members to a team using the Microsoft Graph API. Whether adding a single user, multiple users, or bulk-importing from a CSV file, this script simplifies the process and allows IT admins to save valuable time.

The Script:


    # Microsoft Graph API connection
    Connect-MgGraph -Scopes "Group.ReadWrite.All"
    Write-Host "Connected to Microsoft Graph"

    # Function to add a single member to a team
    function Add-SingleMember {
        $teamId = Read-Host "Enter the Team ID"
        $userId = Read-Host "Enter the User Principal Name (email) or User ID of the member to add"

        $user = Get-MgUser -UserId $userId
        if ($user) {
        New-MgGroupMember -GroupId $teamId -DirectoryObjectId $user.Id
        Write-Host "Member $userId has been added to the team."
        } else {
        Write-Host "User $userId not found."
        }
    }

    # Function to add multiple members to a team
    function Add-MultipleMembers {
        $teamId = Read-Host "Enter the Team ID"
        $userPrincipalNames = Read-Host "Enter User Principal Names (emails) separated by commas"

        $userList = $userPrincipalNames -split ","
        foreach ($userId in $userList) {
        $user = Get-MgUser -UserId $userId.Trim()
        if ($user) {
        New-MgGroupMember -GroupId $teamId -DirectoryObjectId $user.Id
        Write-Host "Member $userId has been added to the team."
        } else {
        Write-Host "User $userId not found."
        }
        }
    }

    # Function to bulk add members to a team from a CSV file
    function Bulk-ImportMembers {
        $teamId = Read-Host "Enter the Team ID"
        $filePath = Read-Host "Enter the CSV file path (the file should contain a 'UserPrincipalName' column)"

        if (Test-Path $filePath) {
        $csvData = Import-Csv -Path $filePath
        foreach ($row in $csvData) {
        $userId = $row.UserPrincipalName
        $user = Get-MgUser -UserId $userId
        if ($user) {
        New-MgGroupMember -GroupId $teamId -DirectoryObjectId $user.Id
        Write-Host "Member $userId has been added to the team."
        } else {
        Write-Host "User $userId not found."
        }
        }
        } else {
        Write-Host "The specified CSV file path does not exist."
        }
    }

    # Main Script Loop
    while ($true) {
        Write-Host "`nChoose an action to add team members:"
        Write-Host "1. Add a single member"
        Write-Host "2. Add multiple members"
        Write-Host "3. Bulk import members from CSV"
        Write-Host "4. Exit"
        $choice = Read-Host "Enter the number corresponding to your choice"

        switch ($choice) {
        "1" { Add-SingleMember }
        "2" { Add-MultipleMembers }
        "3" { Bulk-ImportMembers }
        "4" { Write-Host "Exiting..."; break }
        default { Write-Host "Invalid choice, please try again." }
        }
    }

    # Disconnect from Microsoft Graph
    Disconnect-MgGraph
    Write-Host "Disconnected from Microsoft Graph"


See the Script in Action by clicking and playing these GIFs:

How the Script Works

This script provides an interactive way for administrators to manage Microsoft 365 Team members. Here's how the script works:

  • Connect to Microsoft Graph: The script begins by connecting to the Microsoft Graph API with the necessary Group.ReadWrite.All permissions.
  • Add-SingleMember: This function adds a single user to a team by prompting the admin for the UserPrincipalName or User ID. After verifying the user, it adds them to the specified team.
  • Add-MultipleMembers: This function allows adding multiple members by entering comma-separated UserPrincipalNames. It loops through each user, verifies them, and adds them to the team.
  • Bulk-ImportMembers: This function enables bulk import from a CSV file, which must contain a UserPrincipalName column. For each user listed in the CSV, the script verifies their existence and adds them to the team.
  • Main Menu: The script provides an interactive menu that allows the admin to choose an action (add single member, multiple members, or bulk import) or exit the script. It will continue to prompt until the admin chooses to exit.

Further Enhancements

There are several ways to further enhance this script for more robust Microsoft 365 Teams management:

  • Error Handling Improvements: Adding specific error handling to catch and display more meaningful messages can enhance usability, especially when dealing with large teams.
  • Progress Logging: For bulk operations, add logging to track the progress of each addition, particularly useful for audit trails.
  • CSV Export for Unadded Users: Automatically generate a CSV of any users who could not be added, perhaps due to invalid UserPrincipalNames, which simplifies further investigation.
  • Add Role-Based Assignment: Extend the script to allow assigning specific roles (e.g., Owner, Member) to each added user, providing even more control.

Possible Errors & Solutions

  • Get-MgUser : Not Found
    • Cause: This occurs if the specified UserId (either UserPrincipalName or User ID) is incorrect or does not exist in Azure AD.
    • Solution: Double-check the spelling of the UserPrincipalName or verify that the user exists in Azure AD using Get-MgUser.
    • 
          # Verify User
          Get-MgUser -UserId "user@domain.com"
      
  • PermissionDenied
    • Cause: This error occurs if the admin’s account does not have Group.ReadWrite.All permissions.
    • Solution: Ensure that the account has the correct permissions. If necessary, re-authenticate and provide the necessary permissions in Azure AD.
  • Invalid CSV Path
    • Cause: This happens if the specified file path for the CSV file does not exist or is misspelled
    • Solution: Confirm that the file path is correct and that the file contains a valid UserPrincipalName column.

Conclusion

This PowerShell script is an effective tool for managing team members in Microsoft Teams. It simplifies the process of adding users, whether one at a time, in groups, or through bulk imports from a CSV file. With the ability to scale, automate, and customize this process, admins can save valuable time and reduce the chances of error when managing team memberships. With additional enhancements like improved error handling and logging, this script becomes a powerful solution for efficient and error-free team management.

Suggested Reading

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