使用 PowerShell 從使用者帳戶移除 Microsoft 365 授權

本文適用於 Microsoft 365 企業版和 Office 365 企業版。

使用 Microsoft Graph PowerShell SDK

首先, 聯機到您的 Microsoft 365 租使用者

指派和移除用戶的授權需要 User.ReadWrite.All 許可權範圍或 [指派授權] 圖形 API 參考頁面中所列的其他許可權之一。

需要 Organization.Read.All 許可權範圍,才能讀取租用戶中可用的授權。

Connect-Graph -Scopes User.ReadWrite.All, Organization.Read.All

若要檢視貴組織的授權方案資訊,請參閱下列文章:

從用戶帳戶移除授權

若要從現有的使用者帳戶移除授權,請使用下列語法:

Set-MgUserLicense -UserId "<Account>" -RemoveLicenses @("<AccountSkuId1>") -AddLicenses @{}

此範例會從使用者BelindaN@litwareinc.com移除SPE_E5 (Microsoft 365 E5) 授權方案:

$e5Sku = Get-MgSubscribedSku -All | Where SkuPartNumber -eq 'SPE_E5'
Set-MgUserLicense -UserId "belindan@litwareinc.com" -RemoveLicenses @($e5Sku.SkuId) -AddLicenses @{}

若要從現有授權使用者群組中移除所有授權,請使用下列語法:

$licensedUsers = Get-MgUser -Filter 'assignedLicenses/$count ne 0' `
    -ConsistencyLevel eventual -CountVariable licensedUserCount -All `
    -Select UserPrincipalName,DisplayName,AssignedLicenses

foreach($user in $licensedUsers)
{
    $licensesToRemove = $user.AssignedLicenses | Select -ExpandProperty SkuId
    $user = Set-MgUserLicense -UserId $user.UserPrincipalName -RemoveLicenses $licensesToRemove -AddLicenses @{} 
}

若要從文字檔中的使用者清單中移除特定授權,請執行下列步驟。 本範例會從文本檔 C:\My Documents\Accounts.txt 中定義的使用者帳戶中移除 SPE_E5 (Microsoft 365 企業版 E5) 授權。

  1. 建立文本檔並將其儲存至 C:\My Documents\Accounts.txt,其中每一行各包含一個帳戶,如下所示:

    akol@contoso.com
    tjohnston@contoso.com
    kakers@contoso.com
    
  2. 使用下列命令:

    $x=Get-Content "C:\My Documents\Accounts.txt"
    $e5Sku = Get-MgSubscribedSku -All | Where SkuPartNumber -eq 'SPE_E5'
    for ($i=0; $i -lt $x.Count; $i++)
    {
    Set-MgUserLicense -UserId $x[$i] -RemoveLicenses @($e5Sku.SkuId) -AddLicenses @{}
    }
    

另一種釋出授權的方式是刪除用戶帳戶。 如需詳細資訊,請參閱 使用PowerShell刪除和還原用戶帳戶

另請參閱

以 PowerShell 管理 Microsoft 365 使用者帳戶、授權和群組

使用 PowerShell 管理 Microsoft 365

開始使用適用於 Microsoft 365 的 PowerShell