使用Az PowerShell为托管标识分配Directory Readers角色时遇"角色未找到"错误
解决Azure用户托管标识分配Directory Readers角色的PowerShell方法
问题根源
New-AzRoleAssignment是用于管理Azure资源RBAC角色的命令,而Directory Readers属于Azure AD内置目录角色,二者分属不同权限体系,因此用Az模块的命令无法找到该角色。
解决方案1:使用AzureAD模块
- 安装并导入AzureAD模块:
Install-Module -Name AzureAD -Force Import-Module AzureAD
- 连接到Azure AD:
Connect-AzureAD
- 获取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 }
- 将角色分配给用户托管标识(替换
<UMI-ObjectId>为实际的托管标识ObjectId):
Add-AzureADDirectoryRoleMember -ObjectId $directoryReaderRole.ObjectId -RefObjectId "<UMI-ObjectId>"
解决方案2:使用Microsoft Graph PowerShell模块(推荐)
Microsoft Graph模块是AzureAD模块的替代方案,更符合微软未来技术路线:
- 安装并导入Microsoft Graph模块:
Install-Module -Name Microsoft.Graph -Force Import-Module Microsoft.Graph.Identity.DirectoryManagement
- 连接到Microsoft Graph,需
RoleManagement.ReadWrite.Directory权限:
Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory"
- 获取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 }
- 分配角色给托管标识(替换
<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
相关产品推荐
相关产品推荐

