Get-MgUserMemberOf: How to Retrieve User Group Memberships in Microsoft 365

This guide explains how to use Get-MgUserMemberOf cmdlet in Microsoft Graph PowerShell to retrieve the groups and teams the user belongs to. Learn how to filter results and export membership details with practical examples.

The Get-MgUserMemberOf cmdlet is part of the Microsoft Graph PowerShell module. It retrieves a list of directory objects that a user is a member of. This can include groups, administrative units, and directory roles. In this article, we will explore its syntax, provide usage examples, discuss common errors, and offer some tips for effective usage.


Syntax

Get-MgUserMemberOf -UserId <String> [-Filter <String>] [-Search <String>] [-OrderBy <String>] [-Select <String[]>] [-ExpandProperty <String[]>] [-Top <Int32>] [-Skip <Int32>] [-All] [-ConsistencyLevel <String>] [-CountVariable <String>] [<CommonParameters>]

Parameters

  • -UserId: Specifies the ID or user principal name (UPN) of the user. This parameter is required.
  • -Filter: Filters the results using OData v4 query options.
  • -Search: Searches for objects that match the given query.
  • -Select: Specifies the properties to include in the response.
  • -ExpandProperty: Expands related entities inline.
  • -Top: Limits the number of results returned.
  • -Skip: Skips the first n results.
  • -All: Retrieves all results.
  • -ConsistencyLevel: Sets the consistency level of the request.
  • -CountVariable: Specifies a variable in which to store the total count of objects.

Usage Examples


Example 1: Retrieve all groups a user is a member of

Get-MgUserMemberOf -UserId "john.doe@contoso.com" -All

This command retrieves all groups a user is a member of.


Example 2: Retrieving Display Name for Each Group

$userId = "samadmin@7xh7fj.onmicrosoft.com"

# 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
$detailedGroups | Format-Table -Property DisplayName, Id -AutoSize

This script retrieves all directory objects the user is a member of, iterates through each member object, retrieves detailed information about the group including the DisplayName and Id, and displays the detailed information in a table format.


Example 3: Retrieve a specific number of groups

Get-MgUserMemberOf -UserId "john.doe@contoso.com" -Top 3

This command retrieves the top 3 groups a user is a member of.


Example 4: Filter and Export Groups to CSV

$userId = "john.doe@contoso.com"
$groups = Get-MgUserMemberOf -UserId $userId -All

$groups | Export-Csv -Path "C:\UserGroups\SalesTeamGroups.csv" -NoTypeInformation

This script retrieves all groups a user is a member of and exports the results to a CSV file.


Example 5: Handle Throttling with Retry Logic

function Get-UserGroupsWithRetry {
    param (
        [string]$UserId
        [int]$RetryCount = 3,
        [int]$DelaySeconds = 5
    )

    $attempts = 0
    $success = $false
    while (-not $success -and $attempts -lt $RetryCount) {
        try {
            $groups = Get-MgUserMemberOf -UserId $UserId -All
            $success = $true
        } catch {
            $attempts++
            Write-Warning "Attempt $attempts failed. Retrying in $DelaySeconds seconds..."
            Start-Sleep -Seconds $DelaySeconds
        }
    }

    if ($success) {
        return $groups
    } else {
        throw "Failed to retrieve user groups after $RetryCount attempts."
    }
}

$userId = "john.doe@contoso.com"
$userGroups = Get-UserGroupsWithRetry -UserId $userId

This function implements retry logic with exponential backoff to handle throttling when retrieving user groups.


Cmdlet Tips

  • Use Select Wisely: Use the -Select parameter to retrieve only the properties you need. This can improve performance by reducing the amount of data returned.
  • Filtering: Use the -Filter parameter to narrow down results, especially useful in large environments.
  • Consistency: When using filters, adding the -ConsistencyLevel eventual parameter ensures that results are consistent with the state of the directory.
  • Pagination: Combine -Top and -Skip parameters to handle pagination and retrieve large sets of data in manageable chunks.

Possible Errors and Solutions


Error: Authentication Issues

Cause: "Authorization_RequestDenied"

Solution: Ensure you have the necessary permissions to access the Microsoft Graph API. You might need to consent to the required permissions or update your access token.


Error: Invalid UserId

Cause: "Resource 'userId' not found"

Solution: Verify that the user ID or UPN is correct. Check for typos or incorrect identifiers.


Error: Invalid Filter Syntax

Cause: "Invalid filter clause"

Solution: Check the syntax of your filter. Ensure you are using valid OData v4 query options. Refer to the OData query documentation for details.


Error: Throttling

Cause: "Too Many Requests"

Solution: Implement retry logic with exponential backoff in your scripts to handle throttling. Reduce the frequency of your requests.


Error: Timeouts

Cause: "Request timeout"

Solution: Increase the timeout value for your request. Optimize your queries to return only the necessary data.


Frequently Asked Questions

1. What is Get-MgUserMemberOf used for?

Get-MgUserMemberOf is a Microsoft Graph PowerShell cmdlet used to retrieve the directory objects (e.g., groups, teams, or roles) that a specific user is a member of in a Microsoft 365 tenant.

2. How can I retrieve all group memberships for a specific user?

Use the following command to list all groups a user belongs to:

Get-MgUserMemberOf -UserId "<UserPrincipalName>"

3. Can I filter the results to include only security groups?

Yes, you can filter the results after retrieval by checking the OdataType property. Example:

$Memberships = Get-MgUserMemberOf -UserId "<UserPrincipalName>"
$SecurityGroups = $Memberships | Where-Object { $_.OdataType -eq '#microsoft.graph.group' -and $_.SecurityEnabled -eq $true }

4. How can I export user group memberships to a CSV file?

Use this script to export the user’s memberships:

$Memberships = Get-MgUserMemberOf -UserId "<UserPrincipalName>"
$Memberships | Select-Object DisplayName, OdataType | Export-Csv -Path "C:\Path\To\Memberships.csv" -NoTypeInformation                                

5. What permissions are required to use Get-MgUserMemberOf?

You need the User.Read.All or User.ReadWrite.All permission in Microsoft Graph PowerShell. Ensure these permissions are granted before running the cmdlet.

Conclusion

The Get-MgUserMemberOf cmdlet is essential for retrieving directory objects a user is a member of in Microsoft 365. Utilizing parameters like -Filter, -Select, and -ExpandProperty allows for efficient data retrieval tailored to your needs. Ensure proper permissions and roles to avoid access issues.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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