A cloud-based identity and access management service for securing user authentication and resource access
Hello @BCAzure01,
To get all groups that multiple users belong to at once, make use of below script:
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.Read.All","Group.Read.All" | Out-Null
# Input CSV of users (must have column: Email)
$inputPath = "C:\Users\rukmini\Downloads\importfile.csv"
# Output CSV path
$outputPath = "C:\Users\rukmini\Downloads\GroupMembershipReport.csv"
# Initialize output file (clear if exists)
if (Test-Path $outputPath) { Remove-Item $outputPath }
# Create the header for the CSV file
"EmployeeEmail,GroupName,GroupID,Mail,MailEnabled,SecurityEnabled,GroupType" | Out-File -FilePath $outputPath -Encoding UTF8
# Load users from the input CSV
$users = Import-Csv $inputPath
foreach ($user in $users) {
$email = $user.Email.Trim()
Write-Host "`nProcessing user: $email..."
try {
# Get user information by email
$userObj = Get-MgUser -Filter "userPrincipalName eq '$email'" -Property Id, DisplayName, Mail
if (-not $userObj) { $userObj = Get-MgUser -Filter "mail eq '$email'" -Property Id, DisplayName, Mail }
if ($userObj) {
# Get all groups the user is a member of
$groups = Get-MgUserMemberOfAsGroup -UserId $userObj.Id -Property "id,displayName,mail,mailEnabled,securityEnabled,groupTypes"
foreach ($group in $groups) {
# Classify the group type
$type = if ($group.GroupTypes -contains "Unified") { "Microsoft 365" }
elseif ($group.MailEnabled -and $group.SecurityEnabled) { "Mail-enabled Security" }
elseif ($group.SecurityEnabled) { "Security" }
elseif ($group.MailEnabled) { "Distribution" }
else { "Other" }
# Prepare the output as a CSV row
$row = "$email,$($group.DisplayName),$($group.Id),$($group.Mail),$($group.MailEnabled),$($group.SecurityEnabled),$type"
# Append the row to the CSV file
$row | Out-File -FilePath $outputPath -Append -Encoding UTF8
}
} else {
Write-Warning "User not found: $email"
}
}
catch {
Write-Warning "Error processing $($email): $_"
}
}
Write-Host "`nProcessing complete for all users. Results saved to: $outputPath"
The exported output CSV file:
The import file looks like below:
Hope this helps!
If this answers your query, do click Accept Answer and Yes, if you have any further queries do let us know.
If you have any other questions, let me know in the “comments” and I would be happy to help you.