使用 PowerShell 将管理员角色分配给 Microsoft 365 用户帐户

此文章适用于 Microsoft 365 企业版和 Office 365 企业版。

可以使用适用于 Microsoft 365 的 PowerShell 轻松将角色分配给用户帐户。

注意

了解如何使用 Microsoft 365 管理中心将管理员角色分配给用户帐户。

有关其他资源的列表,请参阅 管理用户和组

使用 Microsoft Graph PowerShell 将角色分配给用户帐户

注意

Azure Active Directory 模块将替换为 Microsoft Graph PowerShell SDK。 可以使用 Microsoft Graph PowerShell SDK 访问所有 Microsoft Graph API。 有关详细信息,请参阅 Microsoft Graph PowerShell SDK 入门

首先,使用 Microsoft Entra DC 管理员云应用程序管理员全局管理员帐户连接到 Microsoft 365 租户。 本文中的 cmdlet 需要权限范围 RoleManagement.ReadWrite.Directory“List subscribedSkus”图形 API参考页中列出的其他权限之一。 本文中的某些命令可能需要不同的权限范围,在这种情况下,相关部分将对此进行说明。

Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory"

有关详细信息,请参阅 关于管理员角色

接下来,确定要添加到角色的用户帐户的登录名, (示例: fredsm@contoso.com) 。 这也称为 UPN) (用户主体名称。

接下来,确定角色的名称。 请参阅Microsoft Entra内置角色

注意

请注意本文中的说明。 Azure Active Directory (Azure AD) PowerShell 的某些角色名称不同。 例如,Microsoft 365 管理中心中的 SharePoint 管理员角色是 Azure AD PowerShell 中的 SharePoint 服务管理员

接下来,填写用户 UPN 和角色名称,并运行以下命令:

$userUPN="<user UPN>"
$roleName="<role name>"
$role = Get-MgDirectoryRole | Where-Object {$_.displayName -eq $roleName}
if ($role -eq $null) {
    $roleTemplate = (Get-MgDirectoryRoleTemplate | Where-Object {$_.displayName -eq $roleName}).id
    New-MgDirectoryRole -DisplayName $roleName -RoleTemplateId $roleTemplate
    $role = Get-MgDirectoryRole | Where-Object {$_.displayName -eq $roleName}
}
$userId = (Get-MgUser -Filter "userPrincipalName eq '$userUPN'").Id
$newRoleMember =@{
    "@odata.id"= "https://graph.microsoft.com/v1.0/users/$userId"
    }
New-MgDirectoryRoleMemberByRef -DirectoryRoleId $role.Id -BodyParameter $newRoleMember

下面是将 SharePoint 服务管理员角色分配给 belindan@contoso.com 帐户的已完成命令集的示例:

$userUPN="adelev@contoso.com"
$roleName="Exchange Administrator"
$role = Get-MgDirectoryRole | Where-Object {$_.displayName -eq $roleName}
if ($role -eq $null) {
    $roleTemplate = (Get-MgDirectoryRoleTemplate | Where-Object {$_.displayName -eq $roleName}).id
    New-MgDirectoryRole -DisplayName $roleName -RoleTemplateId $roleTemplate
    $role = Get-MgDirectoryRole | Where-Object {$_.displayName -eq $roleName}
}
$userId = (Get-MgUser -Filter "userPrincipalName eq '$userUPN'").Id
$newRoleMember =@{
    "@odata.id"= "https://graph.microsoft.com/v1.0/users/$userId"
    }
New-MgDirectoryRoleMemberByRef -DirectoryRoleId $role.Id -BodyParameter $newRoleMember

若要显示特定管理员角色的用户 ID 列表,请使用以下命令。

$roleName="<role name>"
Connect-MgGraph -Scopes "Directory.Read.All"
Get-MgDirectoryRole | Where-Object { $_.DisplayName -eq $roleName } | ForEach-Object { Get-MgDirectoryRoleMember -DirectoryRoleId $_.Id }

另请参阅