Using Get-MgDirectoryRole with Get-MgUser: Efficiently Manage Role Assignments

Roles and permissions in Microsoft 365 are crucial for managing user access and maintaining organizational security. The Get-MgDirectoryRole cmdlet provides insights into roles, their members, and assignments, while the Get-MgUser cmdlet allows administrators to retrieve detailed user information. By combining these cmdlets, you can generate comprehensive reports on role assignments and ensure proper access management across your environment.

This guide demonstrates how to use these cmdlets together to efficiently manage and audit role assignments.

Usage Examples

Retrieve All Role Assignments and Export to a CSV File

The following script fetches directory roles, retrieves their members, and exports detailed role assignments to a CSV file:

# Retrieve all directory roles and expand their members
$directoryRoles = Get-MgDirectoryRole -ExpandProperty Members
$roleReport = @()
                                
foreach ($role in $directoryRoles) {
        # Check if the role has members
        if ($role.Members) {
        foreach ($member in $role.Members) {
            try {
                # Retrieve member details only if it's a user
                if ($member["@odata.type"] -eq "#microsoft.graph.user") {
                $memberDetails = Get-MgUser -UserId $member.Id -Property "displayName, userPrincipalName"
                $roleReport += [PSCustomObject]@{
                    RoleName      = $role.DisplayName
                    MemberName    = $memberDetails.DisplayName
                    MemberUPN     = $memberDetails.UserPrincipalName
                    MemberType    = "User"
                }
                } else {
                # Handle non-user members (e.g., groups, service principals)
                $roleReport += [PSCustomObject]@{
                            RoleName      = $role.DisplayName
                            MemberName    = "Non-User Object"
                            MemberUPN     = "-"
                            MemberType    = $member["@odata.type"] -split "\." | Select-Object -Last 1
                            }
                        }
                        } catch {
                            # Handle errors and log warnings for unresolved members
                            Write-Warning "Could not retrieve details for MemberId: $($member.Id)"
                         }
                        }
                        } else {
                            Write-Warning "No members found for role: $($role.DisplayName)"
                        }
}
                                
# Export the role assignment details to a CSV file
$roleReport | Export-Csv -Path "RoleAssignmentDetails.csv" -NoTypeInformation
                                

Script Output

Use Cases

  • Generate Role Assignment Reports for Compliance: Use the script to generate a CSV report showing role assignments for users and groups. This report can be shared during audits or security reviews.
  • Review and Validate Role Assignments: Identify and confirm the roles assigned to key personnel, such as Global Administrators or Exchange Administrators, to ensure that permissions align with job responsibilities.
  • Troubleshoot Access Issues: Quickly identify whether a user or group is assigned the necessary roles to perform their tasks.
  • Audit Non-User Members in Roles:Detect service principals or groups assigned to roles and verify their necessity to reduce unnecessary role assignments.

Tips and Best Practices

  • Expand Properties for Complete Data: Use the -ExpandProperty Members parameter with Get-MgDirectoryRole to retrieve detailed membership information directly.
  • Filter Data for Specific Needs: Apply filters such as -Filter "displayName eq 'RoleName'" to narrow down results for specific roles.
  • Handle Large Data Sets with Pagination: If working with a large number of roles or members, ensure you implement pagination or use batching to avoid throttling issues.
  • Incorporate Error Handling: Add error handling to manage scenarios where certain objects (e.g., orphaned members) cannot be resolved:
  • try {
    $memberDetails = Get-MgUser -UserId $member.Id
    } catch {
            Write-Warning "Could not retrieve details for MemberId: $($member.Id)"
    }
                                    
    
  • Include Object Types:Distinguish between users, groups, and service principals by analyzing the @odata.type property of each member.

Possible Errors & Solutions

Error Cause Solution
Insufficient privileges to complete the operation. Missing permissions like RoleManagement.Read.Directory or Directory.Read.All. Grant the required permissions in Azure AD for the application or account running the script.
Resource does not exist or one of its queried reference-property objects are not present. The member ID references a deleted or inaccessible object. Skip such objects and log warnings for review.
Request is too large to process. Fetching too much data at once. Use pagination or apply filters to limit the scope of the query.

Conclusion

Using Get-MgUser with Get-MgDirectoryRole empowers administrators to manage and audit role assignments in Microsoft 365 efficiently. This approach allows you to generate detailed reports, troubleshoot access issues, and ensure proper role assignments across your organization. By following the provided examples and best practices, you can enhance security and streamline your role management workflows.

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