Azure自动化Runbook中Get-AzRoleAssignment无法返回指定字段数据
Azure自动化Runbook获取RBAC角色分配时用户信息为空的问题
问题现象
本地使用个人账号(Microsoft Entra认证)执行Get-AzRoleAssignment并导出Excel,能正常获取DisplayName、SignInName、ObjectType等字段;但通过Azure自动化PowerShell Runbook(托管身份)执行时,导出的CSV中DisplayName、SignInName为空,ObjectType全部显示Unknown。已添加AzureAD、EntraIDTools模块,问题仍未解决。
原因分析
托管身份默认没有读取Microsoft Entra ID(原Azure AD)中用户/组对象信息的权限,Get-AzRoleAssignment仅能获取到角色分配的核心数据,无法自动从Entra ID拉取对应的用户/组显示名称、登录名等属性,导致相关字段缺失或显示异常。
解决方案
1. 给托管身份分配Entra ID读取权限
进入Microsoft Entra ID → 角色和管理员 → 搜索并添加目录读取者角色到自动化账户的系统托管身份(或用户托管身份);也可配置最小权限:给托管身份分配仅读取用户、组对象的自定义权限。
2. 修改Runbook代码,手动补全Entra ID属性
通过Get-AzureADUser/Get-AzureADGroup命令手动查询Entra ID数据,补全角色分配中的用户/组信息。
修改后的Runbook代码
# Add needed variables Param ( [Parameter (Mandatory= $true)] [String] $StorageAccountName ) # Connect using Managed Service Identity for Azure Resource Manager try { $AzureContext = (Connect-AzAccount -Identity).context } catch{ Write-Output "无系统分配的托管身份,终止执行。"; exit } # Connect to Microsoft Entra ID using Managed Identity try { Connect-AzureAD -Identity | Out-Null } catch { Write-Output "托管身份无Entra ID访问权限,终止执行。" exit } # Get all role assignments and enrich with Entra ID properties $roleAssignments = Get-AzRoleAssignment | ForEach-Object { $objId = $_.ObjectId $displayName = $null $signInName = $null $objectType = $null # Try to get user first try { $user = Get-AzureADUser -ObjectId $objId -ErrorAction Stop $displayName = $user.DisplayName $signInName = $user.UserPrincipalName $objectType = "User" } catch { # If not user, try group try { $group = Get-AzureADGroup -ObjectId $objId -ErrorAction Stop $displayName = $group.DisplayName $objectType = "Group" } catch { # Keep original values if neither user nor group $displayName = $_.DisplayName $objectType = $_.ObjectType } } # Output the enriched object [PSCustomObject]@{ RoleAssignmentId = $_.RoleAssignmentId Scope = $_.Scope DisplayName = $displayName SignInName = $signInName RoleDefinitionName = $_.RoleDefinitionName RoleDefinitionId = $_.RoleDefinitionId ObjectId = $objId ObjectType = $objectType CanDelegate = $_.CanDelegate } } # Export to CSV $csvPath = Join-Path -Path $env:TEMP2 -ChildPath "MT_AZRoleAssigments.csv" $roleAssignments | Export-Csv -Path $csvPath -Encoding ASCII -NoTypeInformation # Upload to Storage Account $storageContext = New-AzStorageContext -StorageAccountName $StorageAccountName Set-AzStorageBlobContent -Context $storageContext -Container "compliance" -File $csvPath -Blob "MT_AZRoleAssigments.csv" -Force
注意事项
- 确保自动化账户已安装
AzureAD模块;若使用Microsoft Graph API,需安装Microsoft.Graph.Users/Microsoft.Graph.Groups模块,并给托管身份分配User.Read.All、Group.Read.All权限 - 托管身份的权限变更需等待数分钟才能生效
内容的提问来源于stack exchange,提问作者Carlos Samayoa
相关产品推荐
相关产品推荐

