You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Get-AzRoleAssignment查询DisplayName为空,如何获取该字段值?

解决Azure PowerShell查询角色分配时DisplayName为空的问题

当使用Get-AzRoleAssignment查询指定资源组的角色分配信息时,部分条目的DisplayName字段为空,示例输出如下:

DisplayName        : 
RoleDefinitionName : Monitoring Contributor
Scope              : /providers/Microsoft.Management/managementGroups/xxxxx

原因分析

这种情况多发生在角色分配的主体是服务主体、托管标识、Azure AD组,或者分配作用域为管理组层级(该分配继承到目标资源组)时,默认查询结果不会自动填充完整的显示名称,需要主动查询Azure AD获取主体详情。

解决方案

修改脚本,通过ObjectId和ObjectType字段查询对应主体的显示名称,脚本示例:

$resourceGroupName = "az-dna-xxxxx-test"

$roleAssignments = Get-AzRoleAssignment -ResourceGroupName $resourceGroupName
 
foreach ($assignment in $roleAssignments) {
    $displayName = $assignment.DisplayName

    # 当DisplayName为空时,根据主体类型查询Azure AD获取名称
    if ([string]::IsNullOrEmpty($displayName)) {
        switch ($assignment.ObjectType) {
            "ServicePrincipal" {
                $sp = Get-AzADServicePrincipal -ObjectId $assignment.ObjectId
                $displayName = $sp.DisplayName
            }
            "Group" {
                $group = Get-AzADGroup -ObjectId $assignment.ObjectId
                $displayName = $group.DisplayName
            }
            "User" {
                $user = Get-AzADUser -ObjectId $assignment.ObjectId
                $displayName = $user.DisplayName
            }
            "ManagedIdentity" {
                $mi = Get-AzADServicePrincipal -ObjectId $assignment.ObjectId
                $displayName = $mi.DisplayName
            }
            default {
                $displayName = "未知主体类型: $($assignment.ObjectType)"
            }
        }
    }

    Write-Host "DisplayName: $displayName"
    Write-Host "角色定义名称: $($assignment.RoleDefinitionName)"
    Write-Host "作用域: $($assignment.Scope)"
    Write-Host "---"
}

补充说明

  • 执行脚本前需确保当前账号拥有Azure AD目录读取权限(比如Directory Readers角色),否则无法查询Azure AD主体信息
  • 托管标识属于特殊的服务主体,因此用Get-AzADServicePrincipal查询即可获取其显示名称

内容的提问来源于stack exchange,提问作者Meghana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:28:23