Understanding who holds privileged roles in your Microsoft 365 tenant is crucial for maintaining security and compliance. This script leverages Microsoft Graph PowerShell to map role names to their assigned users, groups, or service principals with full clarity and flexibility.
# Connect to Microsoft Graph with necessary scopes
Connect-MgGraph -Scopes "RoleManagement.Read.Directory", "Directory.Read.All"
# Get all role definitions
$roleDefinitions = Get-MgRoleManagementDirectoryRoleDefinition -All
# Get all role assignments
$roleAssignments = Get-MgRoleManagementDirectoryRoleAssignment -All
# Prepare result array
$results = @()
foreach ($assignment in $roleAssignments) {
$roleId = $assignment.RoleDefinitionId
$principalId = $assignment.PrincipalId
$scope = $assignment.DirectoryScopeId
$role = $roleDefinitions | Where-Object { $_.Id -eq $roleId }
$principal = Get-MgDirectoryObject -DirectoryObjectId $principalId
$principalType = $principal.AdditionalProperties.'@odata.type'
$principalName = ''
switch ($principalType) {
'#microsoft.graph.user' {
$user = Get-MgUser -UserId $principalId
$principalName = $user.DisplayName
$principalType = "User"
}
'#microsoft.graph.group' {
$group = Get-MgGroup -GroupId $principalId
$principalName = $group.DisplayName
$principalType = "Group"
}
'#microsoft.graph.servicePrincipal' {
$sp = Get-MgServicePrincipal -ServicePrincipalId $principalId
$principalName = $sp.DisplayName
$principalType = "Service Principal"
}
default {
$principalName = "Unknown"
}
}
$results += [PSCustomObject]@{
RoleName = $role.DisplayName
PrincipalType = $principalType
PrincipalName = $principalName
Scope = $scope
}
}
# Output to table
$results | Format-Table -AutoSize
# Optional: Export to CSV
# $results | Export-Csv -Path "RoleAssignmentsReport.csv" -NoTypeInformation
The output is formatted into a clean table for review or export.
| Error | Cause | Solution |
| Access Denied or Insufficient privileges | Missing required Graph permissions | Use: -Scopes "RoleManagement.Read.Directory", "Directory.Read.All" when connecting |
| Get-MgDirectoryObject : Resource not found | Principal ID might be invalid or object deleted | Skip or log unresolved objects; add error handling |
| Rate limit exceeded | Too many Graph calls in a short time | Introduce Start-Sleep delays or use batching if scaling |
Microsoft Graph PowerShell makes it easier than ever to consolidate, report, and act upon Azure AD role assignments. This script not only simplifies mapping but also ensures you're fully aware of who has elevated access across your tenant. With just a few cmdlets, you're empowered to maintain tighter control and visibility over privileged roles.
© m365corner.com. All Rights Reserved. Design by HTML Codex