Fetch Distribution Group Details with Member Count Using Graph PowerShell

Managing distribution groups in Microsoft 365 can be time-consuming, especially when you need to check group details and member counts. Instead of manually clicking through each distribution group in the admin center, this PowerShell script automates the process and retrieves all the required information in one go. With this script, you can quickly fetch distribution group names, emails, mail nicknames, and member counts using Microsoft Graph PowerShell.

PowerShell Script to List Distribution Groups and Member Count

# Connect to Microsoft Graph (Uncomment if not connected)
# Connect-MgGraph -Scopes "Group.Read.All"
                                
# Retrieve all groups with relevant properties
$allGroups = Get-MgGroup -All -Property DisplayName, Mail, MailNickname, GroupTypes, Id
                                
# Identify Distribution Groups (GroupTypes is empty/null)
$distributionGroups = $allGroups | Where-Object { $_.Mail -ne $null -and ($_.GroupTypes -eq $null -or $_.GroupTypes.Count -eq 0) }
                                
if ($distributionGroups.Count -eq 0) {
    Write-Host "No distribution groups found!" -ForegroundColor Yellow
} else {
    # Output Header
    Write-Host "`nDistribution Groups Report`n" -ForegroundColor Cyan
    Write-Host "-------------------------------------------------------------"
                                
foreach ($group in $distributionGroups) {
    # Ensure GroupId is not null or empty
    $memberCount = "N/A"  # Default value if ID is missing
                                
        if (![string]::IsNullOrEmpty($group.Id)) {
            try {
                # Get member count only if ID is valid
                $memberCount = (Get-MgGroupMember -GroupId $group.Id -All).Count
            } catch {
                Write-Host "Warning: Could not retrieve members for group '$($group.DisplayName)'" -ForegroundColor Red
            }
            } else {
                Write-Host "Warning: Skipping group '$($group.DisplayName)' due to missing ID" -ForegroundColor Red
        }
                                
    # Output group details
    Write-Host "Group Name      : $($group.DisplayName)"
    Write-Host "Group Mail      : $($group.Mail)"
    Write-Host "Mail Nick Name  : $($group.MailNickname)"
    Write-Host "Members (Count) : $memberCount"
    Write-Host "-------------------------------------------------------------"
}
}
                            

How the Script Works

Step 1: Connecting to Microsoft Graph

  • The script requires the Group.Read.All permission.
  • Ensure that the Microsoft Graph module is installed and authenticated using Connect-MgGraph.

Step 2: Retrieving All Groups

  • The script fetches all groups using Get-MgGroup -All -Property DisplayName, Mail, MailNickname, GroupTypes, Id.

Step 3: Filtering Distribution Groups

  • Microsoft 365 Distribution Groups do not have values in the GroupTypes property.
  • The script filters groups where GroupTypes is either null or empty.

Step 4: Retrieving Member Count

  • For each valid distribution group, the script queries members using Get-MgGroupMember -GroupId $group.Id -All.
  • If Id is missing, it safely skips that group to avoid errors.

Step 5: Displaying Results

  • The script neatly formats and outputs:
    • Group Name
    • Group Mail
    • Mail Nickname
    • Member Count

Further Enhancements

  1. Export Data to CSV
  2. Modify the script to save the output as a CSV file:

    $distributionGroups | Select-Object DisplayName, Mail, MailNickname, @{Name='MemberCount';Expression={(Get-MgGroupMember -GroupId $_.Id -All).Count}} | Export-Csv -Path "DistributionGroups.csv" -NoTypeInformation
  3. Filter by Group Name
  4. Allow filtering groups based on keywords:

    $filteredGroups = $distributionGroups | Where-Object { $_.DisplayName -match "Marketing" }
  5. Retrieve Additional Group Properties
  6. Extend the properties fetched using:

    -Property DisplayName, Mail, MailNickname, CreatedDateTime, Description

Possible Errors and Solutions

Error Message Cause Solution
Cannot bind argument to parameter 'GroupId' because it is an empty string. Some groups might have an empty Id Ensure Id is not null before calling Get-MgGroupMember. The script already implements this fix.
Request_UnsupportedQuery The script initially tried filtering groupTypes directly via -Filter, which Graph API does not support The filtering is now done in PowerShell instead of using -Filter.
Warning: Could not retrieve members for group There might be permission issues Ensure you have GroupMember.Read.All or Group.Read.All permissions assigned to your Graph PowerShell session.
No distribution groups found! The GroupTypes value might be different in your tenant Run a debug check using `$allGroups

Conclusion

This Graph PowerShell script provides a reliable method to list distribution groups and count their members. Since GroupTypes for distribution lists is null, we filter them based on this property. The script also ensures robustness by handling missing Id values and avoiding crashes.

Key Takeaways:

  • Uses Microsoft Graph PowerShell to retrieve groups.
  • Filters only distribution groups (via null GroupTypes).
  • Retrieves group details and member count efficiently.
  • Handles errors gracefully to avoid script failure.
  • Easily extendable for exporting data or additional filtering.

Administrators can use this script as-is or enhance it further to suit their needs.

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