🔧 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

Fetch and Mail User Group Memberships With Graph PowerShell

As part of Microsoft 365 administration, it is often necessary to know which groups a particular user belongs to. This information is vital for security reviews, access audits, and compliance tracking. With Microsoft Graph PowerShell, you can automate this task to fetch a user’s group memberships and send the report directly to an administrator’s inbox.

Below is a script that retrieves all group memberships of a specific user, exports them into a CSV file, and emails the report to the administrator.


i) Script



# ============================
# Config
# ============================
# Target user (UPN or ObjectId)
$UserId   = "user@yourtenant.onmicrosoft.com"      
$AdminUPN="admin@yourtenant.onmicrosoft.com" # <-- replace

# Connect to Microsoft Graph
# Scopes: read user/group membership + send mail
Connect-MgGraph -Scopes "User.Read.All","Group.Read.All","Directory.Read.All","Mail.Send"

# ============================
# 1) Fetch membership (your working logic)
# ============================

# Get the list of objects the user is a member of
$memberOf = Get-MgUserMemberOf -UserId $UserId -All

# Initialize an array to store the detailed group information
$detailedGroups = @()

# Loop through each member object and get additional details
foreach ($object in $memberOf) {
    $groupId = $object.Id

    try {
        # Get detailed information about the group
        $group = Get-MgGroup -GroupId $groupId -Select DisplayName, Id
        $detailedGroups += $group
    } catch {
        Write-Warning "Could not retrieve details for group with ID: $groupId"
    }
}

# Display the detailed group information (console)
$detailedGroups | Format-Table -Property DisplayName, Id -AutoSize

# ============================
# 2) Export to CSV
# ============================
$SafeUser = ($UserId -replace '[^\w\.-]', '_')
$ReportPath = "$env:TEMP\GroupMemberships_$SafeUser.csv"

$detailedGroups |
    Select-Object DisplayName, Id |
    Export-Csv -Path $ReportPath -NoTypeInformation -Encoding UTF8

# ============================
# 3) Email the report to admin
# ============================
$groupCount = @($detailedGroups).Count
$Subject = "Group Memberships for $UserId — $(Get-Date -Format 'yyyy-MM-dd')"
$Body = @"
Hello Admin,

Attached is the group membership report for $UserId.
Total groups: $groupCount.

Regards,
Graph PowerShell Script "@ # Attach the CSV $AttachmentContent = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($ReportPath)) $Attachments = @( @{ "@odata.type" = "#microsoft.graph.fileAttachment" Name = [System.IO.Path]::GetFileName($ReportPath) ContentBytes = $AttachmentContent } ) # Build the message payload $Message = @{ Message = @{ Subject = $Subject Body = @{ ContentType = "HTML" Content = $Body } ToRecipients = @( @{ EmailAddress = @{ Address = $AdminUPN } } ) Attachments = $Attachments } SaveToSentItems = "true" } # Send the email from admin's mailbox Send-MgUserMail -UserId $AdminUPN -BodyParameter $Message Write-Host "Group membership report for $UserId emailed successfully to $AdminUPN"

ii) How the Script Works

  1. Configuration – The script requires two values:
    • The target user ($UserId – can be UPN or ObjectId).
    • The administrator’s mailbox ($AdminUPN) to receive the report.
  2. Connect to Microsoft Graph – It authenticates using the required scopes:
    • User.Read.All → read user data.
    • Group.Read.All & Directory.Read.All → read group memberships.
    • Mail.Send → send the report via email.
  3. Fetch Membership – Using Get-MgUserMemberOf, it retrieves all objects the user is a member of. For each object, Get-MgGroup fetches the Display Name and Group ID.
  4. Export Report – Group membership details are exported to a CSV file in the temp directory.
  5. Email the Report – The CSV file is attached to an HTML-based email and sent to the administrator.

iii) Further Enhancements

  • Include More Group Details – Add fields like GroupType, Visibility, or MailEnabled for richer reporting.
  • Support Multiple Users – Extend the script to process a list of users (via CSV import).
  • Automated Scheduling – Run the script daily or weekly using Task Scheduler or Azure Automation.
  • Centralized Storage – Store reports in OneDrive or SharePoint instead of sending them by email.
  • Audit Trail – Log the results into a monitoring system for compliance tracking.

iv) Possible Errors & Solutions

Error Cause Solution
Insufficient privileges to complete the operation Missing Graph API scopes. Connect with User.Read.All, Group.Read.All, Directory.Read.All, and Mail.Send.
Send-MgUserMail : Resource not found Invalid $AdminUPN value. Ensure $AdminUPN is a valid mailbox-enabled account.
Could not retrieve details for group with ID … The object is not a group (could be a directory role or other object). This is expected. Non-group objects can be skipped safely.
Empty CSV File The user does not belong to any groups. Verify user memberships. The script will still generate a valid empty file.

v) Conclusion

This script provides administrators with a quick and automated way to fetch and review a user’s group memberships. By exporting the results and sending them via email, it removes manual effort and ensures that admins always have access to updated group membership data.

With a few enhancements such as adding more properties, processing multiple users, or automating on a schedule, this script can evolve into a powerful reporting and auditing tool for Microsoft 365 environments


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