使用 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,或 [列出 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

若要顯示特定系統管理員角色的使用者標識碼清單,請使用這些命令。

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

另請參閱