Get-MgGroupMember: How to List and Manage Microsoft 365 Group Members

"This article provides a detailed walkthrough for using Get-MgGroupMember cmdlet in Graph PowerShell. You’ll learn how to retrieve group members, filter them by properties like role and export the results for reporting"

This guide covers the prerequisites, syntax, usage examples, and potential errors while retrieving group membership details within your Microsoft 365 environment.


Prerequisites

Ensure you have the Microsoft.Graph module installed and authenticated to your Microsoft 365 tenant.

# Install the Microsoft.Graph module if not already installed
Install-Module Microsoft.Graph -Scope CurrentUser

# Import the module
Import-Module Microsoft.Graph

# Authenticate to Microsoft 365
Connect-MgGraph -Scopes "Group.Read.All"

Cmdlet Syntax

Get-MgGroupMember
   -GroupId <String>
   [-ExpandProperty <String[]>]
   [-Filter <String>]
   [-Property <String[]>]
   [-Search <String>]
   [-Skip <Int32>]
   [-Sort <String[]>]
   [-Top <Int32>]
   [-ConsistencyLevel <String>]
   [-ResponseHeadersVariable <String>]
   [-Headers <IDictionary>]
   [-PageSize <Int32>]
   [-All]
   [-CountVariable <String>]
   [-ProgressAction <ActionPreference>]
   [<CommonParameters>]

Parameters

  • -GroupId <String>: The unique identifier of the group. This is a required parameter.
  • -ExpandProperty <String[]>: Expand related entities. For example, expanding members of the group.
  • -Filter <String>: Filter items by property values. However, not all properties are supported for filtering.
  • -Property <String[]>: Select properties to be returned. Specify which properties you want to include in the results.
  • -Search <String>: Search items by search phrases. Useful for finding members based on specific criteria.
  • -Skip <Int32>: Skip the first n items. Useful for paging through large sets of results.
  • -Sort <String[]>: Order items by property values. For example, sorting members by their displayName.
  • -Top <Int32>: Show only the first n items. Limits the number of results returned.
  • -ConsistencyLevel <String>: Indicates the requested consistency level. Useful for advanced queries requiring a specific consistency level.
  • -ResponseHeadersVariable <String>: Stores response headers in a variable.
  • -Headers <IDictionary>: Optional headers that will be added to the request.
  • -PageSize <Int32>: Sets the page size of results. Controls the number of items per page.
  • -All: Lists all pages. Retrieves all members, not just the first page of results.
  • -CountVariable <String>: Specifies a count of the total number of items in a collection. By default, this variable will be set in the global scope.
  • -ProgressAction <ActionPreference>: Defines the action preference for progress updates.
  • Common Parameters: Supports common parameters like -Debug, -ErrorAction, -Verbose, etc. for better error handling and debugging.

Usage Examples


Example 1: Get Members of a Group

Retrieve all members of a specified group.

Get-MgGroupMember -GroupId "<GroupId>"
PowerShell command retrieving members of a Microsoft 365 group

Example 2: Search Members

Search for group members using a specific search string.

Get-MgGroupMember -GroupId "<GroupId>" -Search "displayName:John" -ConsistencyLevel eventual
PowerShell output displaying group members filtered by display name 'Jackie'

Example 3: Top Members

Retrieve the top N members of the group.

Get-MgGroupMember -GroupId "<GroupId>" -Top 10
PowerShell command fetching top 2 members of a Microsoft 365 group

Example 4: Sort Members

Sort the group members based on a specific property.

Get-MgGroupMember -GroupId "<GroupId>" -Sort "displayName asc" -ConsistencyLevel eventual -CountVariable groupCount
PowerShell script for sorting group members in ascending order

Example 5: Select Group Member User Properties

Retrieve the group members and then fetch their displayName and userPrincipalName:

# Retrieve members of a specified group
$groupMembers = Get-MgGroupMember -GroupId "1cbe8c31-589d-453a-a1e5-045f7f00c967"

# Initialize an array to store detailed user information
$userDetails = @()

# Loop through each group member and retrieve additional properties
foreach ($member in $groupMembers) {
    $user = Get-MgUser -UserId $member.Id -Property "id, displayName, userPrincipalName"
    $userDetails += [PSCustomObject]@{
        Id                 = $user.Id
        DisplayName        = $user.DisplayName
        UserPrincipalName  = $user.UserPrincipalName
    }
}

# Display the detailed user information
$userDetails | Select-Object Id, DisplayName, UserPrincipalName
PowerShell command for selecting and displaying member id, displayname and userprinicipalname

Example 6: Retrieve Group Owners and Group Members

Retrieve Group Owners and Group Members separately. Get-MgGroupOwner cmdlet helps you get the Group Owner(s).

# Retrieve owners of the specified group
$groupOwners = Get-MgGroupOwner -GroupId "1cbe8c31-589d-453a-a1e5-045f7f00c967"

# Retrieve members of the specified group
$groupMembers = Get-MgGroupMember -GroupId "1cbe8c31-589d-453a-a1e5-045f7f00c967"

# Display group owners
"Group Owners:"
$groupOwners | Select-Object Id, DisplayName, UserPrincipalName

# Display group members
"Group Members:"
$groupMembers | Select-Object Id, DisplayName, UserPrincipalName
PowerShell output showing group owner and member IDs separately

Viewing Group Members Using Admin Center

To view group members using the admin center, you should select the Group >> Membership tab >> then select Members option.

Microsoft 365 admin center interface displaying group membership tab

Use-Cases

Managing Group Memberships in Large Organizations

In large organizations, managing group memberships effectively is crucial for maintaining security and ensuring that users have the correct access rights. Here are some use cases and best practices for managing large groups using the Get-MgGroupMember cmdlet:

  1. Audit Group Memberships Regularly:
    • Use Case: Periodically auditing group memberships can help ensure that only the appropriate users have access to sensitive resources.
    • Best Practice: Schedule automated scripts that run the Get-MgGroupMember cmdlet to export group membership details to a CSV file. Review this file regularly to spot any discrepancies or outdated memberships.
    • Get-MgGroupMember -GroupId $GroupId -All | Export-Csv -Path "GroupMembers.csv" -NoTypeInformation
  2. Automating Onboarding and Offboarding:
    • Use Case: Automating the addition and removal of group members during onboarding and offboarding processes.
    • Best Practice: Integrate the Get-MgGroupMember cmdlet with other automation tools to streamline the process. For instance, you can check if a user is already a member before adding them to avoid errors.
    • 
          $user = Get-MgUser -UserId "new.employee@company.com"
          if (-not (Get-MgGroupMember -GroupId $GroupId -UserId $user.Id)) {
          Add-MgGroupMember -GroupId $GroupId -UserId $user.Id
          }
      
  3. Handling Large Groups:
    • Use Case: Managing groups with thousands of members can be challenging due to performance and throttling limits.
    • Best Practice: Implement pagination and retry logic to handle large sets of data efficiently. Consider breaking down operations into smaller batches to avoid throttling.
    • 
          $top = 100
          $GroupId = "large-group-id"
          $members = Get-MgGroupMember -GroupId $GroupId -Top $top
      
          do {
          $members | ForEach-Object {
          # Process each member
          }
          $members = Invoke-RestMethod -Uri $members.'@odata.nextLink' -Headers @{Authorization = "Bearer $($token)"}
          } while ($members.'@odata.nextLink')
      
  4. Cross-Group Membership Reporting:
    • Use Case: Reporting on users who are members of multiple groups, which is essential for access management and compliance.
    • Best Practice: Use PowerShell scripts to compare memberships across different groups and identify overlaps. This is particularly useful in auditing and compliance scenarios.
    • 
          $groupIds = @("group1-id", "group2-id")
          $allMembers = @()
      
          foreach ($groupId in $groupIds) {
          $members = Get-MgGroupMember -GroupId $groupId -All
          $allMembers += $members
          }
      
          $duplicateMembers = $allMembers | Group-Id | Where-Object { $_.Count -gt 1 }
      
  5. Identifying Unnecessary Access:
    • Use Case: Identify users who no longer need access to a group by reviewing the membership data.
    • Best Practice: Comparing group membership against a list of users who should have access, and then removing unauthorized users:
    • 
          $authorizedUsers = @("user1@domain.com", "user2@domain.com")
          $groupMembers = Get-MgGroupMember -GroupId $GroupId -All
      
          $groupMembers | ForEach-Object {
              if ($authorizedUsers -notcontains $_.UserPrincipalName) {
              Remove-MgGroupMember -GroupId $GroupId -UserId $_.Id
          }
          }
      


Possible Errors and Solutions


Invalid Group ID

Error: The specified group ID is invalid.

Solution: Ensure the GroupId parameter is correct and the group exists in your tenant.

Insufficient Permissions

Error: Insufficient privileges to complete the operation.

Solution: Ensure you have the required permissions. You might need Group.Read.All or similar permissions.

Property Not Found

Error: The property specified in the -Property parameter does not exist.

Solution: Verify the property names and ensure they are valid for the group members.

Filter Syntax Error

Error: Syntax error in the -Filter parameter.

Solution: Ensure the filter syntax follows the OData query language. Refer to the OData query documentation for correct syntax.

Request Throttling

Error: Request Throttling

Description: When working with large groups, you might encounter throttling issues due to the high number of API requests.

Cause: Microsoft Graph imposes limits on API calls to prevent overuse.

Solution: Implement a retry mechanism in your script to handle throttling. For example:

try {
      $members = Get-MgGroupMember -GroupId $GroupId
    } catch [System.Exception] {
      Write-Warning "Request throttled. Waiting 60 seconds before retrying..."
      Start-Sleep -Seconds 60
      $members = Get-MgGroupMember -GroupId $GroupId
}

Cmdlet Tips

  • Paging Through Results: Use the -PageSize parameter to control the number of results returned per page.
  • Consistency Level: Use the -ConsistencyLevel parameter with the value eventual for queries that require a count of the results.
  • Common Parameters: Utilize common parameters like -Debug, -ErrorAction, and -Verbose for better error handling and debugging.

Frequently Asked Questions

What is Get-MgGroupMember used for?

Get-MgGroupMember is a Microsoft Graph PowerShell cmdlet that retrieves members of a specified group in Microsoft 365. It supports filtering by member type (e.g., user, service principal) and exporting results for further analysis.

Can I filter members by role using Get-MgGroupMember?

No, Get-MgGroupMember does not natively support filtering by role (e.g., owners). However, you can achieve this using a workaround. For example, retrieve all members, then filter locally in PowerShell:


    $GroupId = "<GroupId>"
    $Members = Get-MgGroupMember -GroupId $GroupId
    $Owners = $Members | Where-Object { $_.Role -eq "Owner" }

How can I export the list of group members to a CSV file?

Use the following script to export group members to a CSV file:


    $GroupId = "<GroupId>"
    $Members = Get-MgGroupMember -GroupId $GroupId -All
    $Members | Select-Object Id, DisplayName, UserPrincipalName | Export-Csv -Path


Conclusion

The Get-MgGroupMember cmdlet is a versatile tool for managing and retrieving group members in Microsoft 365 using Microsoft Graph PowerShell. By understanding its syntax and parameters, you can efficiently manage group memberships and integrate these commands into your automation scripts. Use the examples and best practices provided to get started today!

For more detailed information, visit the Microsoft documentation.


Suggested Reading

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