使用 PowerShell 封鎖 Microsoft 365 用戶帳戶

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

當您封鎖對 Microsoft 365 帳戶的存取時,您會防止任何人使用該帳戶來登入和存取 Microsoft 365 組織中的服務和數據。 您可以使用 PowerShell 來封鎖對個別或多個使用者帳戶的存取。

封鎖對個別用戶帳戶的存取

注意事項

Azure Active Directory 模組正由 Microsoft Graph PowerShell SDK 取代。 您可以使用 Microsoft Graph PowerShell SDK 來存取所有的 Microsoft Graph API。 如需詳細資訊,請參閱 開始使用 Microsoft Graph PowerShell SDK

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

封鎖和解除封鎖用戶帳戶需要 User.ReadWrite.All 許可權範圍或 [列出 subscribedSkus] 參考頁面中所列的其中一個其他許可權 圖形 API。

Connect-Graph -Scopes User.ReadWrite.All

使用下列語法來封鎖個別用戶帳戶:

$params = @{
	accountEnabled = $false
}
Update-MgUser -UserId <sign-in name of the user account> -BodyParameter $params

注意事項

Update-MgUser Cmdlet 中的 -UserId 參數會接受帳戶登入名稱,也稱為用戶主體名稱或帳戶的對象標識碼。

此範例會封鎖對用戶帳戶的存 fabricec@litwareinc.com取。

$params = @{
	accountEnabled = $false
}
Update-MgUser -UserId "fabricec@litwareinc.com" -BodyParameter $params

若要將使用者帳戶解除封鎖,請執行下列命令:

$params = @{
	accountEnabled = $true
}
Update-MgUser -UserId "fabricec@litwareinc.com" -BodyParameter $params

若要根據使用者的顯示名稱顯示使用者帳戶 UPN,請使用下列命令:

$userName="<display name>"
Write-Host (Get-MgUser -All | where {$_.DisplayName -eq $userName}).UserPrincipalName

此範例會顯示使用者 Caleb Sills 的用戶帳戶 UPN。

$userName="Caleb Sills"
Write-Host (Get-MgUser -All | where {$_.DisplayName -eq $userName}).UserPrincipalName

若要根據使用者的顯示名稱封鎖帳戶,請使用下列命令:

$userName="<display name>"
$user = Get-MgUser -Filter "displayName eq '$userName'"
$params = @{
	accountEnabled = $false
}
Update-MgUser -UserId $user.Id -BodyParameter $params

若要檢查使用者帳戶的封鎖狀態,請使用下列命令:

Get-MgUser -ObjectID <UPN of user account> -Property "displayName,accountEnabled" | Select displayName, accountEnabled

封鎖多個用戶帳戶

若要封鎖多個用戶帳戶的存取,請建立一個文本檔,其中包含每一行的一個帳戶登入名稱,如下所示:

akol@contoso.com
tjohnston@contoso.com
kakers@contoso.com

在下列命令中,範例文字檔為 C:\My Documents\Accounts.txt。 將此檔案名取代為文字檔的路徑和檔名。

若要封鎖對文字檔中所列帳戶的存取,請執行下列命令:

$params = @{
	accountEnabled = $false
}
Get-Content "C:\My Documents\Accounts.txt" | ForEach {Update-MgUser -UserId $_ -BodyParameter $params}

若要解除封鎖文字檔中列出的帳戶,請執行下列命令:

$params = @{
	accountEnabled = $true
}
Get-Content "C:\My Documents\Accounts.txt" | ForEach {Update-MgUser -UserId $_ -BodyParameter $params}

另請參閱

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

使用 PowerShell 管理 Microsoft 365

開始使用適用於 Microsoft 365 的 PowerShell