Manage Microsoft 365 Groups with Graph PowerShell

Managing Microsoft 365 Groups is a vital task for administrators who want to streamline collaboration across their organization. This can involve tasks like creating new groups, updating group details, listing all groups, or even deleting unnecessary ones. Microsoft Graph PowerShell offers a powerful way to automate these tasks efficiently.

In this article, we will explore a Graph PowerShell based script designed to manage Microsoft 365 Groups. It helps Microsoft 365 administrator perform the following actions: 1) List all groups, 2) Create a new group, 3) Update an existing group’s description and 4) Delete a group. The 5th option exits the script.

The Script:


    # Ensure the Microsoft Graph PowerShell module is installed and imported
    if (-not (Get-Module -ListAvailable -Name "Microsoft.Graph")) {
        Install-Module -Name "Microsoft.Graph" -Scope CurrentUser
    }
    Import-Module Microsoft.Graph

    Connect-MgGraph -Scopes "Group.ReadWrite.All"

    # Function to list all M365 Groups
    function Get-AllGroups {
    try {
        Get-MgGroup -All | ForEach-Object {
        [PSCustomObject]@{
        DisplayName    = $_.DisplayName
        MailNickname   = $_.MailNickname
        Description    = $_.Description
        GroupId        = $_.Id
        GroupType      = $_.GroupTypes
    }
    } | Format-Table -AutoSize
    } catch {
        Write-Host "Error retrieving groups: $($_.Exception.Message)" -ForegroundColor Red
    }
    }

    # Function to create a new M365 Group
    function New-M365Group {
    $groupDisplayName = Read-Host "Enter the group display name"
    $groupMailNickname = Read-Host "Enter the group mail nickname"
    $groupDescription = Read-Host "Enter the group description"
    $groupVisibility = Read-Host "Enter group visibility (Private/Public)"

    try {
        $groupParams = @{
        displayName = $groupDisplayName
        mailEnabled = $true
        mailNickname = $groupMailNickname
        securityEnabled = $false
        description = $groupDescription
        groupTypes = @("Unified")
        visibility = $groupVisibility
    }
    $newGroup = New-MgGroup -BodyParameter $groupParams
    Write-Host "New Group Created: $($newGroup.Id)"
    } catch {
        Write-Host "Error creating group: $($_.Exception.Message)" -ForegroundColor Red
    }
    }

    # Function to update M365 Group details
    function Update-M365Group {
    $groupDisplayName = Read-Host "Enter the current group display name"
    $newGroupDescription = Read-Host "Enter the new description for the group"

    try {
        $groupId = (Get-MgGroup -Filter "displayName eq '$groupDisplayName'").Id
        if ($groupId) {
        $groupParams = @{
        description = $newGroupDescription
        }
        Update-MgGroup -GroupId $groupId -BodyParameter $groupParams
        Write-Host "Group updated successfully!"
    } else {
    Write-Host "Group not found!" -ForegroundColor Red
    }
    } catch {
        Write-Host "Error updating group: $($_.Exception.Message)" -ForegroundColor Red
    }
    }

    # Function to delete an M365 Group
    function Remove-M365Group {
    $groupDisplayName = Read-Host "Enter the group display name to delete"

    try {
        $groupId = (Get-MgGroup -Filter "displayName eq '$groupDisplayName'").Id
        if ($groupId) {
        Remove-MgGroup -GroupId $groupId
        Write-Host "Group removed successfully!"
    } else {
    Write-Host "Group not found!" -ForegroundColor Red
    }
    } catch {
        Write-Host "Error deleting group: $($_.Exception.Message)" -ForegroundColor Red
    }
    }

    # Main Menu
    function Show-Menu {
    Write-Host "What action would you like to perform?"
    Write-Host "1. List all groups"
    Write-Host "2. Create a new group"
    Write-Host "3. Update an existing group's description"
    Write-Host "4. Delete a group"
    Write-Host "5. Exit"

    $action = Read-Host "Enter your choice (1-5)"
    return $action
    }

    # Main logic
    do {
    $action = Show-Menu

    switch ($action) {
    1 { Get-AllGroups }
    2 { New-M365Group }
    3 { Update-M365Group }
    4 { Remove-M365Group }
    5 { Write-Host "Exiting script..."; break }
    default { Write-Host "Invalid selection. Please choose a valid option." }
    }

    $continue = Read-Host "Do you want to perform another action? (yes/no)"
    } while ($continue -eq 'yes')


See the Script in Action by clicking and playing this GIF:

How the Script Works

This script provides an interactive way for administrators to manage Microsoft 365 Groups. Here's how each function works:

  • Get-AllGroups: This function retrieves all the available Microsoft 365 Groups in the tenant and displays key properties, such as the display name, mail nickname, description, and group type, in a neatly formatted table.
  • New-M365Group: : This function guides the admin through the process of creating a new Microsoft 365 Group. The admin is prompted to input a group display name, mail nickname, description, and visibility (Private/Public). The group is then created with these details.
  • Update-M365Group: This function updates the description of an existing group. The admin is prompted for the current display name of the group and the new description. The group is then updated accordingly.
  • Remove-M365Group: This function deletes an existing group. The admin provides the display name of the group they want to delete, and the group is then removed.
  • Main Menu: The script offers a simple menu to choose between listing, creating, updating, and deleting groups. The admin can perform multiple actions in a single session, repeating as necessary.

Further Enhancements

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

  • Adding Group Owners: After creating a group, an option could be added to assign owners dynamically. Owners could be specified through email or UPN.
  • CSV Import for Bulk Operations: Instead of inputting one group at a time, the script can be modified to read a CSV file to create or update multiple groups in bulk.
  • Error Logging: Enhance the script to log any errors encountered during execution, along with detailed error messages, to a file for easier troubleshooting.
  • Advanced Filtering: The Get-AllGroups function could be extended to allow filtering based on properties such as visibility, groupType, or createdDateTime.

Possible Errors & Solutions

  • Invalid Property 'owners': If you encounter this error during group creation, ensure you’ve removed the owners property from the group creation body parameter. This script no longer includes it, but it can be added separately later.
  • BadRequest (400): This error occurs when the input for group properties like mailNickname or visibility is incorrect. Always ensure that the inputs conform to the allowed values (for example, visibility should be either "Private" or "Public").
  • Group Not Found: If the script cannot find the group to update or delete, double-check the spelling of the group display name. This function uses an exact match, so case and spaces must match the actual group name.
  • Insufficient Permissions: Ensure you have the appropriate Graph API permissions assigned, specifically Group.ReadWrite.All. Without this permission, you may encounter authorization errors.

Conclusion

With this interactive Microsoft 365 Group management script, administrators can streamline group creation, updating, listing, and deletion processes using Microsoft Graph PowerShell. The script is flexible, allowing you to add additional features, such as bulk operations and error logging, to tailor it to your organization's needs. By handling key management tasks directly from the command line, administrators can save time and reduce the chances of manual errors. Keep this script handy for your day-to-day group management, and enhance it as your needs evolve!

Suggested Reading

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