đź”§ New: User Management Graph PowerShell Toolkit

Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more — all from one place.

🚀 Launch Toolkit

Email Distribution Groups Report with Graph PowerShell

Distribution Groups (DGs) still play a vital role in many Microsoft 365 environments. While Microsoft Teams and Microsoft 365 Groups dominate modern collaboration, classic Distribution Groups remain widely used for email-based communication, especially for departments, mailing lists, or external contact lists. Over time, however, it becomes hard for administrators to keep track of all existing Distribution Groups—their owners, creation dates, or whether they’re still in use.

This Graph PowerShell script makes that task easier. It gathers all Distribution Groups, collects key details like GroupId, DisplayName, Mail, CreatedDate, and Description, exports them to a CSV file, and emails the report to the administrator.


i) Script

# ===== Distribution Groups -> CSV -> Email to Admin =====
# Requires: Microsoft.Graph module
# Scopes: Group.Read.All, Mail.Send
                                
# --- Email variables ---
$FromUser  = "admin@contoso.com"         # Sender (must have mailbox)
$To        = "it-ops@contoso.com"        # Recipient
$Subject   = "Distribution Groups report"
$CsvOutDir = "$env:TEMP"
                                
# --- Connect to Microsoft Graph ---
Import-Module Microsoft.Graph -ErrorAction Stop
Connect-MgGraph -Scopes "Group.Read.All","Mail.Send"
                                
# --- Get all mail-enabled, non-security groups (candidate DGs) ---
$allGroups = Get-MgGroup -All `
-Filter "mailEnabled eq true and securityEnabled eq false" `
-Property Id,DisplayName,Description,Mail,MailEnabled,SecurityEnabled,GroupTypes,CreatedDateTime

# --- Exclude Unified (Microsoft 365) groups; keep classic Distribution Groups only ---
$distributionGroups = $allGroups | Where-Object { $_.GroupTypes -notcontains "Unified" }

# --- Shape data for CSV ---
$rows = $distributionGroups | ForEach-Object {
[PSCustomObject]@{
    GroupId      = $_.Id
    DisplayName  = $_.DisplayName
    Mail         = $_.Mail
    CreatedDate  = $_.CreatedDateTime
    Description  = $_.Description
}
}

# --- Export to CSV ---
if (-not (Test-Path -Path $CsvOutDir)) { New-Item -ItemType Directory -Path $CsvOutDir | Out-Null }
$ts = Get-Date -Format "yyyyMMdd_HHmmss"
$csvPath = Join-Path $CsvOutDir ("Distribution_Groups_{0}.csv" -f $ts)
$rows | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8

# --- Prepare HTML Body ---
$totalDGs = $rows.Count
$summaryHtml = @"
<html>
  <body style='font-family:Segoe UI,Arial,sans-serif'>
    <h3>Distribution Groups Report</h3>
    <p>Total distribution groups: <b>$totalDGs</b></p>
    <p>The full list (with GroupId, Name, Mail, CreatedDate) is attached as a CSV.</p>
  </body>
</html>

"@
                                
# --- Prepare Attachment ---
$fileBytes     = [System.IO.File]::ReadAllBytes($csvPath)
$base64Content = [System.Convert]::ToBase64String($fileBytes)
$csvFileName   = [System.IO.Path]::GetFileName($csvPath)
$attachment = @{
    "@odata.type" = "#microsoft.graph.fileAttachment"
    name          = $csvFileName
    contentBytes  = $base64Content
    contentType   = "text/csv"
}

# --- Prepare and Send Email ---
$mail = @{
    message = @{
    subject = "$Subject"
    body    = @{
        contentType = "HTML"
        content     = $summaryHtml
    }
    toRecipients = @(@{ emailAddress = @{ address = $To } })
    attachments  = @($attachment)
    }
    saveToSentItems = $true
}

Send-MgUserMail -UserId $FromUser -BodyParameter $mail

Write-Host "Done. CSV saved at: $csvPath" -ForegroundColor Green
                            

ii) How the Script Works

  1. Connects to Microsoft Graph
  2. Uses the Graph PowerShell SDK with the scopes Group.Read.All to read group objects and Mail.Send to send the report via email.

  3. Filters for Distribution Groups
  4. Pulls all groups where mailEnabled = true and securityEnabled = false. This ensures only mail-enabled groups are included.

  5. Excludes Microsoft 365 Groups
  6. Removes any groups that have GroupTypes containing "Unified", leaving only classic Distribution Groups.

  7. Prepares the report
  8. Extracts essential details such as GroupId, DisplayName, Mail, CreatedDate, and Description into a clean PSCustomObject.

  9. Exports to CSV and emails it
  10. Saves the report as a timestamped CSV and sends it to the administrator’s mailbox with an HTML summary.


iii) Further Enhancements

  • Add Owners: Include group owners in the CSV for accountability.
  • Member Counts: Add the number of members in each Distribution Group.
  • Age Analysis: Flag older groups for review or decommissioning.
  • Scheduled Reports: Automate daily/weekly runs via Task Scheduler or Azure Automation.
  • Dynamic Delivery: Email reports to multiple admins or a governance DL.

iv) Use Cases

  • Tenant Governance: Maintain a clean inventory of all Distribution Groups.
  • Audit Preparation: Provide reports for compliance or external audits.
  • Lifecycle Management: Identify old or unused groups for removal.
  • Security Oversight: Verify that only approved groups exist in the tenant.

v) Possible Errors & Solutions

Error Cause Solution
Authorization_RequestDenied Missing Graph permissions Connect with Group.Read.All and Mail.Send; ensure admin consent.
Get-MgGroup not recognized Graph module not installed Run Install-Module Microsoft.Graph -Scope CurrentUser.
CSV is empty No Distribution Groups found Confirm DGs exist; check filters and tenant configuration.
Email not sent $FromUser not mailbox-enabled Use a licensed mailbox-enabled account as sender.
Script misses some groups Pagination not handled correctly -All ensures all groups are retrieved.

vi) Conclusion

Distribution Groups are still widely used for email-based communication in Microsoft 365, but without visibility, they can easily grow unchecked. This Graph PowerShell script provides administrators with a full inventory of Distribution Groups, emailed automatically as a CSV report. By scheduling the script and extending it with owners or member counts, IT teams can strengthen governance, simplify audits, and keep their environment clean and compliant.


Graph PowerShell Explorer Widget

20 Graph PowerShell cmdlets with easily accessible "working" examples.


Permission Required

Example:


                


                


                

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