I wrote the following Powershell script for my company to quickly and effectively disable user accounts and revoke all access to our network. It works with AD, Azure AD, Exchange On-Prem (2013+) and Exchange Online.
It works by forcing a password change to something random, disabling the user account, revoking all user groups (except for the default one), blocking the Azure Sign In, and then from there it goes into exchange and blocks all of the users ActiveSync devices.
param (
[string]$ADServer = $env:computername,
[string]$Domain = $env:userdnsdomain,
[string]$ExchangeServer = $env:computername,
[bool]$EXO = $false,
[string]$AADUsername = "",
[string]$Username = $( throw "-username is required." )
)
$FQUsername = "$Username@$Domain"
if ($AADUsername -ne "") {
$AADUsername = $AADUsername
} else {
$AADUsername = $FQUsername
}
# Force a password change
Set-ADAccountPassword -Server $ADServer -Identity $FQUsername -Reset -NewPassword [System.Web.Security.Membership]::GeneratePassword(10, 3)
# Disable the account
Disable-ADAccount -Server $ADServer -Identity $FQUsername
# Remove all groups from user except for the default one
Get-ADPrincipalGroupMembership -Server $ADServer -Identity $FQUsername | Where-Object -Property Name -NE -Value 'Domain Users' | Remove-ADGroupMember -Members $FQUsername
# Block Azure AD Sign In
Connect-AzureAD
Set-AzureADUser -ObjectID $AADUsername -AccountEnabled $false
Revoke-AzureADUserAllRefreshToken -ObjectId $AADUsername
Disconnect-AzureAD
# Block user devices from Exchange ActiveSync, convert to Shared Mailbox
if ($EXO)
{
Connect-ExchangeOnline
Get-EXOMobileDeviceStatistics -Mailbox $AADUsername | ForEach-Object -Process { Set-EXOCASMailbox -Identity $AADUsername -ActiveSyncBlockedDevicesIDs $_.DeviceID }
Set-Mailbox -Identity $AADUsername -Type Shared
}
else
{
$UserCredential = Get-Credential -Message "Please enter your on-prem exchange credentials"
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$ExchangeServer/PowerShell/" -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session -DisableNameChecking
Get-MobileDeviceStatistics -Server $ExchangeServer -Mailbox $FQUsername | ForEach-Object -Process { Set-CASMailbox -Identity $FQUsername -ActiveSyncBlockedDeviceIDs $_.DeviceID }
Set-Mailbox -Identity $FQUsername -Type Shared
Remove-PSSession $Session
}
The following options do the following things:
Parameter | Type | Default | Required | Description |
ADServer | String | $env:computername | false | Regular AD Server |
Domain | String | $env:userdnsdomain | false | On-Prem Domain |
ExchangeServer | String | $env:computername | false | On-Prem Exchange Server |
EXO | Boolean | $false | false | Exchange Online? |
Username | String | null | true | The username of the on-prem user being disabled |
AADUsername | String | null | false | AzureAD full username (including @) if diffrent from on-prem |