Fetch Security Group Members Using Microsoft Graph PowerShell

Security groups in Microsoft 365 are essential for managing user permissions, access control, and security policies. As an administrator, you may need to retrieve a list of users within a security group along with their details for auditing or reporting purposes. In this article, we explore a Graph PowerShell script that fetches security group members and displays their Group Name, Member Name, Department, and Job Title on the console.


Script to Fetch Security Group Members

Below is the PowerShell script that retrieves and displays the Group Name, Member Name, Department, and Job Title of each member in a security group.

# Install & Import Graph Module (if not already installed)
# Install-Module Microsoft.Graph -Scope CurrentUser
Import-Module Microsoft.Graph
                                
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Group.Read.All", "User.Read.All"
                                
# Prompt for Security Group Name or ID
$GroupNameOrId = Read-Host "Enter Security Group Name or Object ID"
                                
# Get Group Details (fetch by name if an ID is not provided)
$Group = Get-MgGroup -Filter "displayName eq '$GroupNameOrId'" -Property Id, DisplayName
                                
if ($Group -eq $null) {
    Write-Host "Error: No security group found with name or ID '$GroupNameOrId'" -ForegroundColor Red
    exit
}
                                
# Fetch Group Members (Only retrieves IDs, so we need to query user details separately)
$Members = Get-MgGroupMember -GroupId $Group.Id -All
                                
if ($Members.Count -eq 0) {
    Write-Host "No members found in the security group '$($Group.DisplayName)'" -ForegroundColor Yellow
} else {
    # Retrieve user details for each member
    $MemberDetails = @()
                                        
    foreach ($Member in $Members) {
    # Fetch full user details
    $User = Get-MgUser -UserId $Member.Id -Property DisplayName, Department, JobTitle
                                    
    # Store details in custom object
    $MemberDetails += [PSCustomObject]@{
    "Group Name"  = $Group.DisplayName
    "Member Name" = $User.DisplayName
    "Department"  = $User.Department
    "Job Title"   = $User.JobTitle
}
}
                                
# Display Results in Table Format
$MemberDetails | Format-Table -AutoSize
}
                                
# Disconnect from Graph
Disconnect-MgGraph
                                

How the Script Works

  1. Connects to Microsoft Graph
  2. Prompts for Security Group Name or Object ID
    • The user enters the display name or object ID of the security group they want to query.
  3. Fetches Group Details
    • The script calls Get-MgGroup to retrieve the group’s ID and display name.
  4. Retrieves Group Members
  5. Fetches Member Details
    • It iterates through each member ID and queries Get-MgUser to retrieve the DisplayName, Department, and JobTitle.
  6. Displays the Output in a Table Format
    • The results are formatted in a structured table for easy readability.
  7. Disconnects from Microsoft Graph
    • The script ends by disconnecting from Microsoft Graph to release the session.

Further Enhancements

Here are some potential improvements to the script:

  • Export Data to CSV: Modify the script to export results using:
  • $MemberDetails | Export-Csv -Path "SecurityGroupMembers.csv" -NoTypeInformation
  • Filter Only User Objects: Some security groups contain devices or service principals. You can modify the script to filter out only users:
  • $UsersOnly = $Members | Where-Object { $_.'@odata.type' -eq '#microsoft.graph.user' }
  • Batch Process Multiple Security Groups: Allow input from a CSV file to retrieve multiple groups at once.
  • Enhance Error Handling: Implement better error handling for cases where API calls fail due to network or permission issues.

Use Cases

  • Security Group Audits: IT admins can verify who has access to specific security groups.
  • User Access Reports: Generate reports on which users belong to which security groups.
  • Compliance & Security Reviews: Ensure that only authorized users are in sensitive security groups.
  • Automated User Management: Integrate with scripts to remove inactive users from security groups.

Frequently Asked Questions

  • Can I retrieve only user objects from a security group?
  • Yes. The Get-MgGroupMember cmdlet can return different object types (users, guests, devices, service principals). To target only user objects, filter results based on @odata.type -eq '#microsoft.graph.user'.

  • How can I export security group members for reporting?
  • You can pipe the output of Get-MgGroupMember into Export-Csv to generate structured reports. For example:

    Get-MgGroupMember -GroupId -All | Export-Csv -Path "C:\GroupMembers.csv" -NoTypeInformation
  • Why do I sometimes see fewer members than expected?
  • By default, the cmdlet may return a limited set of members. Use the -All parameter to fetch the complete membership list, or handle pagination with $skiptoken.

  • Can I check if group members are guest accounts?
  • Yes. After retrieving member IDs, pass them to Get-MgUser and filter by the UserType property to separate guest accounts from members.

Possible Errors & Solutions

Error Cause Solution
Error: No security group found with name or ID The entered name does not match any security group. Verify the group name or use the Object ID instead.
No members found in the security group The group exists but has no members. Check if the group has members and ensure they are not hidden.
Get-MgUser: User Not Found The script tries to fetch details for a non-user object (e.g., a service principal or device). Modify the script to filter only User objects from the group members.
Access Denied The connected account lacks the necessary permissions. Ensure that Group.Read.All and User.Read.All permissions are granted and admin consented.

🔍 Filter to Only User Objects Using @odata.type

Security groups often include non-user objects like service principals or devices. Before fetching user details, filter your members by @odata.type -eq '#microsoft.graph.user' to ensure you're only processing user identities.
📁 Export Results to CSV for Simplified Reporting

Beyond displaying group membership with Format-Table, pipe your results to Export-Csv — a best practice for creating audit-ready or shareable reports.

$MemberDetails | Export-Csv -Path "SecurityGroupMembers.csv" -NoTypeInformation

Conclusion

This PowerShell script provides an efficient way to fetch and display members of a Microsoft 365 security group, including Member Name, Department, and Job Title. By leveraging Microsoft Graph API, administrators can automate security audits, improve user management, and ensure compliance. The script can be further enhanced with CSV exports, error handling, and bulk processing capabilities.


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