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

使用Az PowerShell为托管标识分配Directory Readers角色时遇"角色未找到"错误

解决Azure用户托管标识分配Directory Readers角色的PowerShell方法

问题根源

New-AzRoleAssignment是用于管理Azure资源RBAC角色的命令,而Directory Readers属于Azure AD内置目录角色,二者分属不同权限体系,因此用Az模块的命令无法找到该角色。

解决方案1:使用AzureAD模块

  1. 安装并导入AzureAD模块:
Install-Module -Name AzureAD -Force
Import-Module AzureAD
  1. 连接到Azure AD:
Connect-AzureAD
  1. 获取Directory Readers角色对象,若角色未激活则先激活:
# 尝试获取已激活的角色
$directoryReaderRole = Get-AzureADDirectoryRole | Where-Object {$_.DisplayName -eq "Directory Readers"}

# 如果角色未激活,从模板创建角色实例
if (-not $directoryReaderRole) {
    $roleTemplate = Get-AzureADDirectoryRoleTemplate | Where-Object {$_.DisplayName -eq "Directory Readers"}
    $directoryReaderRole = Enable-AzureADDirectoryRole -RoleTemplateId $roleTemplate.ObjectId
}
  1. 将角色分配给用户托管标识(替换<UMI-ObjectId>为实际的托管标识ObjectId):
Add-AzureADDirectoryRoleMember -ObjectId $directoryReaderRole.ObjectId -RefObjectId "<UMI-ObjectId>"

解决方案2:使用Microsoft Graph PowerShell模块(推荐)

Microsoft Graph模块是AzureAD模块的替代方案,更符合微软未来技术路线:

  1. 安装并导入Microsoft Graph模块:
Install-Module -Name Microsoft.Graph -Force
Import-Module Microsoft.Graph.Identity.DirectoryManagement
  1. 连接到Microsoft Graph,需RoleManagement.ReadWrite.Directory权限:
Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory"
  1. 获取Directory Readers角色定义ID,并检查角色实例是否存在:
$roleDefinitionId = (Get-MgDirectoryRoleDefinition -Filter "displayName eq 'Directory Readers'").Id
$roleInstance = Get-MgDirectoryRole -Filter "roleDefinitionId eq '$roleDefinitionId'"

# 若角色未激活,创建角色实例
if (-not $roleInstance) {
    $roleInstance = New-MgDirectoryRole -RoleDefinitionId $roleDefinitionId
}
  1. 分配角色给托管标识(替换<UMI-ObjectId>):
New-MgDirectoryRoleMemberByRef -DirectoryRoleId $roleInstance.Id -BodyParameter @{
    "@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/<UMI-ObjectId>"
}

注意事项

  • 执行命令的账号需要具备全局管理员或特权角色管理员权限
  • 可通过Get-AzUserAssignedIdentity命令获取用户托管标识的ObjectId

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:56:04