Automating with PowerShell: Quickly offboarding a M365 user

This is a bit of a sidetrack from my usual stuff – I normally focus on the larger and more procedural issues because I always believe that everyone does offboarding/onboarding in a different way, some people create shared mailboxes, others leave the license intact, or something else entirely. But one of my readers asked “Is there any way to create some more automation around that? I hate clicking around in the portal”. I understand where he’s coming from of course.

So, to help him I’ve taught him how to use PowerShell to perform all the tasks he wanted to perform, and he combined that into a single script for his offboarding. I figured that others might also want to learn from this and maybe even create this into an Azure Function for ease of their employees.

I’ve created two versions of the script; one using the secure application model, and another that you can just execute. The script performs the following tasks:

  • Removes the user from all Azure AD groups
  • Removes the user from all Teams
  • Removes the user from all Distribution groups
  • Hides the user from the GAL
  • Converts the user to a shared mailbox
  • Removes the licenses, and prints which license it removed for canceling.

So,let’s get to scripting

Secure Application Model version

Edit this script to your credentials. and your user to offboard, and execute the script.

#########User info######
$userToOffboard = "olduser@oldclient.com"
$CustomerDefaultDomainname = "MyClient.onmicrosoft.com"
######### Secrets #########
$ApplicationId = 'ApplicationID'
$ApplicationSecret = 'ApplicationSecret' | ConvertTo-SecureString -Force -AsPlainText
$RefreshToken = 'RefreshToken'
$ExchangeRefreshToken = 'ExchangeToken'
$UPN = "UPN-Used-to-Generate-Tokens"
######### Secrets #########
write-host "Logging in to M365 using the secure application model" -ForegroundColor Green
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)
$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $CustomerDefaultDomainname 
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $CustomerDefaultDomainname 
write-host "Logging into Azure AD." -ForegroundColor Green
Connect-AzureAD -AadAccessToken $aadGraphToken.AccessToken -AccountId $UPN -MsAccessToken $graphToken.AccessToken -TenantId $CustomerDefaultDomainname
write-host "Connecting to Exchange Online" -ForegroundColor Green
$token = New-PartnerAccessToken -ApplicationId 'a0c73c16-a7e3-4564-9a95-2bdf47383716'-RefreshToken $ExchangeRefreshToken -Scopes 'https://outlook.office365.com/.default' -Tenant $CustomerDefaultDomainname 
$tokenValue = ConvertTo-SecureString "Bearer $($token.AccessToken)" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($upn, $tokenValue)
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell-liveid?DelegatedOrg=$($CustomerDefaultDomainname)&BasicAuthToOAuthConversion=true" -Credential $credential -Authentication Basic -AllowRedirection
Import-PSSession $session -AllowClobber
write-host "Removing users from Azure AD Groups" -ForegroundColor Green
$MemberID = (Get-AzureADUser -ObjectId $userToOffboard).objectId
Get-AzureADUserMembership -ObjectId $MemberID -All $true | Where-Object { $_.ObjectType -eq "Group" -and $_.SecurityEnabled -eq $true -and $_.MailEnabled -eq $false } | ForEach-Object { 
    write-host "    Removing using from $($_.displayname)" -ForegroundColor green
    Remove-AzureADGroupMember -ObjectId $_.ObjectID -MemberId $MemberID
}
write-host "Removing users from Unified Groups and Teams" -ForegroundColor Green
$OffboardingDN = (get-mailbox -Identity $userToOffboard -IncludeInactiveMailbox).DistinguishedName
Get-Recipient -Filter "Members -eq '$OffboardingDN'" -RecipientTypeDetails 'GroupMailbox' | foreach-object { 
    write-host "    Removing using from $($_.name)" -ForegroundColor green
    Remove-UnifiedGroupLinks -Identity $_.ExternalDirectoryObjectId -Links $userToOffboard -LinkType Member -Confirm:$false }

write-host "Removing users from Distribution Groups" -ForegroundColor Green
Get-Recipient -Filter "Members -eq '$OffboardingDN'" | foreach-object { 
    write-host "    Removing using from $($_.name)" -ForegroundColor green
    Remove-DistributionGroupMember -Identity $_.ExternalDirectoryObjectId -Member $OffboardingDN -BypassSecurityGroupManagerCheck -Confirm:$false }

write-host "Setting mailbox to Shared Mailbox" -ForegroundColor Green
Set-Mailbox $userToOffboard -Type Shared
write-host "Hiding user from GAL" -ForegroundColor Green
Set-Mailbox $userToOffboard -HiddenFromAddressListsEnabled $true

write-host "Removing License from user." -ForegroundColor Green
$AssignedLicensesTable = Get-AzureADUser -ObjectId $userToOffboard | Get-AzureADUserLicenseDetail | Select-Object @{n = "License"; e = { $_.SkuPartNumber } }, skuid 
if ($AssignedLicensesTable) {
    $body = @{
        addLicenses    = @()
        removeLicenses = @($AssignedLicensesTable.skuid)
    }
    Set-AzureADUserLicense -ObjectId $userToOffboard -AssignedLicenses $body
}

write-host "Removed licenses:"
$AssignedLicensesTable
Remove-PSSession $session

Manual version

This version you’ll have to enter your credentials twice, once for the Azure AD Module, and another for the Exchange Online module.

#########User info######
$userToOffboard = "olduser@oldclient.com"
$CustomerDefaultDomainname = "MyClient.onmicrosoft.com"
###

write-host "Logging into Azure AD." -ForegroundColor Green
Connect-AzureAD
write-host "Connecting to Exchange Online" -ForegroundColor Green
install-module ExchangeOnlineManagement
connect-exchangeonline
write-host "Removing users from Azure AD Groups" -ForegroundColor Green
$MemberID = (Get-AzureADUser -ObjectId $userToOffboard).objectId
Get-AzureADUserMembership -ObjectId $MemberID -All $true | Where-Object { $_.ObjectType -eq "Group" -and $_.SecurityEnabled -eq $true -and $_.MailEnabled -eq $false } | ForEach-Object { 
    write-host "    Removing using from $($_.displayname)" -ForegroundColor green
    Remove-AzureADGroupMember -ObjectId $_.ObjectID -MemberId $MemberID
}
write-host "Removing users from Unified Groups and Teams" -ForegroundColor Green
$OffboardingDN = (get-mailbox -Identity $userToOffboard -IncludeInactiveMailbox).DistinguishedName
Get-Recipient -Filter "Members -eq '$OffboardingDN'" -RecipientTypeDetails 'GroupMailbox' | foreach-object { 
    write-host "    Removing using from $($_.name)" -ForegroundColor green
    Remove-UnifiedGroupLinks -Identity $_.ExternalDirectoryObjectId -Links $userToOffboard -LinkType Member -Confirm:$false }

write-host "Removing users from Distribution Groups" -ForegroundColor Green
Get-Recipient -Filter "Members -eq '$OffboardingDN'" | foreach-object { 
    write-host "    Removing using from $($_.name)" -ForegroundColor green
    Remove-DistributionGroupMember -Identity $_.ExternalDirectoryObjectId -Member $OffboardingDN -BypassSecurityGroupManagerCheck -Confirm:$false }

write-host "Setting mailbox to Shared Mailbox" -ForegroundColor Green
Set-Mailbox $userToOffboard -Type Shared
write-host "Hiding user from GAL" -ForegroundColor Green
Set-Mailbox $userToOffboard -HiddenFromAddressListsEnabled $true

write-host "Removing License from user." -ForegroundColor Green
$AssignedLicensesTable = Get-AzureADUser -ObjectId $userToOffboard | Get-AzureADUserLicenseDetail | Select-Object @{n = "License"; e = { $_.SkuPartNumber } }, skuid 
if ($AssignedLicensesTable) {
    $body = @{
        addLicenses    = @()
        removeLicenses = @($AssignedLicensesTable.skuid)
    }
    Set-AzureADUserLicense -ObjectId $userToOffboard -AssignedLicenses $body
}

write-host "Removed licenses:"
$AssignedLicensesTable
Remove-PSSession $session

And that’s it! as always, Happy PowerShelling. 🙂

9 Comments

  1. Sam June 29, 2021 at 5:49 pm

    Great stuff. I got it to work with the manual one (assume I have to use the tenant admin rather than my multi tenant one – well I had to)

    I couldn’t get the secure app one to work. I went through secureapp gen multiple times however it did work when I tested on another script that uses secureapp. It was a permissions thing.

    I reckon the two are linked – secureapp will be multi tenant (again assuming) but this script was looking for their tenant admin creds.

    More likely to be my config – but I’m a global admin and partner admin so thought it would work. Passing this on for the rare and low possibility of it being a script error or if you can suggest things for me to check. Be nice to get this going on azure for my other techs to use.

  2. abu July 14, 2021 at 8:57 pm

    Looks great solution, Correct me if i am wrong. is this converted shared mailbox is accessible for someone if need like 1up manager of offboarding user, because it is hidden from GAL

  3. Bronson July 26, 2021 at 7:31 pm

    Do you know of a way to move the users. Onedrive to a SharePoint site? Currently I do this through the portal page.

  4. Kent August 12, 2021 at 7:24 am

    Would be nice to add functionality to grant another existing user permissions to the shared mailbox, with an option to auto-map or not, and also account for transferring ownership of onedrive files, either to the same user, or another user

  5. scott August 12, 2021 at 9:57 am

    Do you know, using this method, we can automate it in some way and get the username and exit date from a list etc thats in sharepoint? That way it can be fully automated

  6. Steef August 20, 2021 at 2:32 am

    I know everyone has different offboarding requirements so it’s not possible to make it perfect for everyone.
    This a great start and will save a lot of mouse clicks.

    To be a perfect script (for me) it would allow me to set a forwarding address, restore all recoverable emails in the deleted folder and export to a PST for archival.
    After a bit of searching, don’t think it’s possible to do the PST from PS.

    1. Kelvin Tegelaar August 25, 2021 at 8:12 pm

      You don’t want to use PSTs in general, PSTs are allowed to have a high % of data loss before being considered corrupt. Try to always avoid them.

  7. Erik Sheldon September 7, 2021 at 2:24 am

    Thank you so much for this! Would love to implement something I could just run against my tenant to remove the users. We run in hybrid AD mode. Will this work in a tenant like that? I’m working on using the secure model script since we use MFA, but having issues with the secrets section. Can you help me figure where to find the information for lines 5-9?

  8. Luis September 13, 2021 at 2:21 am

    So Im having this error come when I run the scrypt myself. Any reason for that and how to avoid it happening?

    Connecting to Exchange Online
    WARNING: The names of some imported commands from the module ‘tmp_g414sohl.z3c’ include unapproved verbs that might
    make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the
    Verbose parameter. For a list of approved verbs, type Get-Verb.
    Account Environment TenantId TenantDomain AccountType
    ——- ———– ——– ———— ———–

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.