Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more — all from one place.
🚀 Launch ToolkitAs 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.
# ============================
# 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"
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. |
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
© m365corner.com. All Rights Reserved. Design by HTML Codex