O365 Admin - User deactivation script

Sun, May 16, 2021 2-minute read

A Powershell script for user deactivation. A quick alternative to using the O365 admin center.

What it does

  • Converts the user to a shared mailbox
  • Removes licenses
  • Sets email forwarding or delegates mailbox permissions
$UserCredential = Get-Credential
Connect-MsolService -Credential $UserCredential

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking

$Deactivate = Read-Host "Which user would you like to deactivate?"
$upn = $Deactivate
(get-MsolUser -UserPrincipalName $upn).licenses.AccountSkuId |
foreach{
    Set-MsolUserLicense -UserPrincipalName $upn -RemoveLicenses $_
}
Set-Mailbox -Identity $Deactivate -Type:Shared

$msg = 'Would you like to set a forwarding address ( y / n )?'
do {
    $response = Read-Host -Prompt $msg
    if ($response -eq 'y') {
        $Forward = Read-Host "Enter the email address."
        Set-Mailbox $Deactivate -ForwardingAddress $Forward

    }
} until ($response -eq 'n'-or $response -eq 'y')

$msg = 'Would you like to set mailbox permissions ( y / n )?'
do {
    $response = Read-Host -Prompt $msg
    if ($response -eq 'y'-or $strQuit -eq 'y') {
        $FullAccess = Read-Host "Enter the email address of the user you wish to give full access to"
        Add-MailboxPermission -Identity $Deactivate -User $FullAccess -AccessRights FullAccess -InheritanceType All
        $strQuit = Read-Host "Would you like to add more permissions?( y / n )"
    }
} until ($strQuit -eq "n"-or $response -eq 'n')

How to use

  1. Copy code to a text file and save with .ps1 extension
  2. Install Powershell Module and set Execution Policy (Set-ExecutionPolicy RemoteSigned, Install-Module MSOnline, Import-Module Msonline)
  3. Execute .ps1 file from powershell
  4. Enter O365 global admin credentials when prompted