Counting Microsoft 365 Groups and Distribution Groups with Graph PowerShell

In Microsoft 365, managing groups is a crucial aspect of maintaining an organized and secure environment. In this article, we will walk you through a Graph PowerShell script that lists the count of security groups and distribution groups within your tenant. We will also explain how the script works, suggest enhancements, discuss possible errors and solutions, and conclude with the importance of such scripts in your daily administrative tasks.


PowerShell Script to Count Security and Distribution Groups

Here’s the script that retrieves the count of security groups and distribution groups:

Connect-MgGraph -Scopes "Group.Read.All"
$allGroups = Get-MgGroup -All -Property DisplayName, MailEnabled, SecurityEnabled, GroupTypes

$m365Groups = $allGroups | Where-Object {
    $_.GroupTypes -contains "Unified"
}

$distributionGroups = $allGroups | Where-Object {
    ($_.MailEnabled -eq $true) -and
    ($_.SecurityEnabled -eq $false) -and
    (-not ($_.GroupTypes -contains "Unified"))
}

Write-Output "Microsoft 365 Groups Count: $($m365Groups.Count)"
Write-Output "Distribution Groups Count: $($distributionGroups.Count)"
Disconnect-MgGraph

Script Output:


How the Script Works

  1. Connect to Microsoft Graph: The script starts by connecting to Microsoft Graph using the Connect-MgGraph cmdlet with the required scope Group.Read.All.
  2. Retrieve All Groups: It then retrieves all groups in the tenant using the Get-MgGroup cmdlet. The -All parameter ensures that all groups are fetched and the -Property GroupTypes parameter ensures that the GroupTypes property is included in the results.
  3. Filter Groups: The script filters the groups into Microsoft 365 groups and distribution groups. Microsoft 365 groups are identified by the presence of "Unified" in the GroupTypes property while distribution groups are identified by "Distribution".
  4. Count Groups: It counts the number of security groups and distribution groups.
  5. Output the Counts: Finally, it outputs the counts of security groups and distribution groups.
  6. Disconnect from Microsoft Graph: The script ends by disconnecting from Microsoft Graph using the Disconnect-MgGraph cmdlet.

Enhancing the Script

Here are a few ways to enhance this script:

  • Include More Group Types: Modify the script to count other group types such as security groups or mail-enabled security groups.
  • Detailed Output: Provide detailed information about each group type, including their names and creation dates.
  • Export Results: Export the results to a CSV file for further analysis or reporting.

Example enhancement to export results:

# Export the group counts to a CSV file
$groupCounts = [PSCustomObject]@{
    SecurityGroupsCount     = $securityGroupCount
    DistributionGroupsCount = $distributionGroupCount
}
$groupCounts | Export-Csv -Path "GroupCounts.csv" -NoTypeInformation

Possible Errors and Solutions

Error: Unauthorized Access

Message:

Connect-MgGraph : Insufficient privileges to complete the operation.

Solution: Ensure that the account you are using has the Group.Read.All permission. You may need to grant the necessary permissions in Azure Active Directory and re-authenticate.

Error: Network Issues

Message:

Connect-MgGraph : A connection attempt failed because the connected party did not properly respond after a period of time or established connection failed because connected host has failed to respond.

Solution: Check your internet connection and ensure that your network allows connections to Microsoft Graph.

Error: Throttling

Message:

Get-MgGroup : Too many requests.

Solution: Implement retry logic with exponential backoff to handle throttling by Microsoft Graph.

Example of retry logic:

$retryCount = 0
$maxRetries = 5
$retryDelay = 2

do {
    try {
        $allGroups = Get-MgGroup -All -Property GroupTypes
        $success = $true
    } catch {
        $retryCount++
        Start-Sleep -Seconds $retryDelay
        $retryDelay *= 2
    }
} until ($success -or $retryCount -ge $maxRetries)

if (-not $success) {
    Write-Error "Failed to retrieve groups after multiple attempts."
    exit
}
📘 Filter with groupTypes/any(c:c eq 'Unified') to Count Microsoft 365 Groups

Microsoft 365 groups are marked with the "Unified" value in the groupTypes property.

Use this filter to accurately count Microsoft 365 groups while excluding mail-enabled security and distribution groups.
✉️ Use mailEnabled eq true and Exclude Unified to Count Distribution Groups

Distribution groups are mail-enabled but do not include "Unified" in their groupTypes.

Filter by mailEnabled eq true and exclude groupTypes/any(c:c eq 'Unified') to separate them from Microsoft 365 groups.

Conclusion

Using Graph PowerShell to manage and report on groups within your Microsoft 365 tenant is a powerful and efficient approach. The script provided in this article helps you quickly ascertain the number of security groups and distribution groups, allowing for better organization and security management. By understanding how to enhance the script and handle potential errors, you can tailor the solution to fit your specific needs and ensure robust group management in your environment.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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