Try the following
Install-Module Microsoft.Graph -Scope CurrentUser
Connect-MgGraph -Scopes "RoleManagement.Read.Directory"
# Function to fetch role members considering Administrative Units
function Get-RoleMembers {
param (
[string]$roleId,
[string]$scope = $null
)
if ($null -ne $scope) {
# Fetch members scoped to an Administrative Unit
$members = Get-MgAdministrativeUnitMember -AdministrativeUnitId $scope
} else {
# Fetch members scoped to the entire directory
$members = Get-MgUser -Filter "assignedRoles/any(x:x/id eq '$roleId')"
}
return $members
}
$result = @()
foreach ($assignment in $roleAssignments) {
$role = $roles | Where-Object {$_.Id -eq $assignment.RoleDefinitionId}
$members = Get-RoleMembers -roleId $role.Id -scope $assignment.DirectoryScopeId
foreach ($member in $members) {
$result += [PSCustomObject]@{
RoleName = $role.DisplayName
RoleId = $role.Id
MemberName = $member.DisplayName
MemberEmail = $member.UserPrincipalName
Scope = $assignment.DirectoryScopeId
}
}
}
# Export the results to a CSV file
$result | Export-Csv -Path "AzureADRoleAssignments.csv" -NoTypeInformation
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin