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"-ForegroundColorGreen$credential=New-ObjectSystem.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$CustomerDefaultDomainnamewrite-host"Logging into Azure AD."-ForegroundColorGreenConnect-AzureAD-AadAccessToken$aadGraphToken.AccessToken-AccountId$UPN-MsAccessToken$graphToken.AccessToken-TenantId$CustomerDefaultDomainnamewrite-host"Connecting to Exchange Online"-ForegroundColorGreen$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-ObjectSystem.Management.Automation.PSCredential($upn,$tokenValue)$session=New-PSSession-ConfigurationNameMicrosoft.Exchange-ConnectionUri"https://ps.outlook.com/powershell-liveid?DelegatedOrg=$($CustomerDefaultDomainname)&BasicAuthToOAuthConversion=true"-Credential$credential-AuthenticationBasic-AllowRedirectionImport-PSSession$session-AllowClobberwrite-host"Removing users from Azure AD Groups"-ForegroundColorGreen$MemberID=(Get-AzureADUser-ObjectId$userToOffboard).objectIdGet-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)"-ForegroundColorgreenRemove-AzureADGroupMember-ObjectId$_.ObjectID-MemberId$MemberID}write-host"Removing users from Unified Groups and Teams"-ForegroundColorGreen$OffboardingDN=(get-mailbox-Identity$userToOffboard-IncludeInactiveMailbox).DistinguishedNameGet-Recipient-Filter"Members -eq '$OffboardingDN'"-RecipientTypeDetails'GroupMailbox'|foreach-object{write-host" Removing using from $($_.name)"-ForegroundColorgreenRemove-UnifiedGroupLinks-Identity$_.ExternalDirectoryObjectId-Links$userToOffboard-LinkTypeMember-Confirm:$false}write-host"Removing users from Distribution Groups"-ForegroundColorGreenGet-Recipient-Filter"Members -eq '$OffboardingDN'"|foreach-object{write-host" Removing using from $($_.name)"-ForegroundColorgreenRemove-DistributionGroupMember-Identity$_.ExternalDirectoryObjectId-Member$OffboardingDN-BypassSecurityGroupManagerCheck-Confirm:$false}write-host"Setting mailbox to Shared Mailbox"-ForegroundColorGreenSet-Mailbox$userToOffboard-TypeSharedwrite-host"Hiding user from GAL"-ForegroundColorGreenSet-Mailbox$userToOffboard-HiddenFromAddressListsEnabled$truewrite-host"Removing License from user."-ForegroundColorGreen$AssignedLicensesTable=Get-AzureADUser-ObjectId$userToOffboard|Get-AzureADUserLicenseDetail|Select-Object@{n="License";e={$_.SkuPartNumber}},skuidif($AssignedLicensesTable){$body=@{addLicenses=@()removeLicenses=@($AssignedLicensesTable.skuid)}Set-AzureADUserLicense-ObjectId$userToOffboard-AssignedLicenses$body}write-host"Removed licenses:"$AssignedLicensesTableRemove-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."-ForegroundColorGreenConnect-AzureADwrite-host"Connecting to Exchange Online"-ForegroundColorGreeninstall-moduleExchangeOnlineManagementconnect-exchangeonlinewrite-host"Removing users from Azure AD Groups"-ForegroundColorGreen$MemberID=(Get-AzureADUser-ObjectId$userToOffboard).objectIdGet-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)"-ForegroundColorgreenRemove-AzureADGroupMember-ObjectId$_.ObjectID-MemberId$MemberID}write-host"Removing users from Unified Groups and Teams"-ForegroundColorGreen$OffboardingDN=(get-mailbox-Identity$userToOffboard-IncludeInactiveMailbox).DistinguishedNameGet-Recipient-Filter"Members -eq '$OffboardingDN'"-RecipientTypeDetails'GroupMailbox'|foreach-object{write-host" Removing using from $($_.name)"-ForegroundColorgreenRemove-UnifiedGroupLinks-Identity$_.ExternalDirectoryObjectId-Links$userToOffboard-LinkTypeMember-Confirm:$false}write-host"Removing users from Distribution Groups"-ForegroundColorGreenGet-Recipient-Filter"Members -eq '$OffboardingDN'"|foreach-object{write-host" Removing using from $($_.name)"-ForegroundColorgreenRemove-DistributionGroupMember-Identity$_.ExternalDirectoryObjectId-Member$OffboardingDN-BypassSecurityGroupManagerCheck-Confirm:$false}write-host"Setting mailbox to Shared Mailbox"-ForegroundColorGreenSet-Mailbox$userToOffboard-TypeSharedwrite-host"Hiding user from GAL"-ForegroundColorGreenSet-Mailbox$userToOffboard-HiddenFromAddressListsEnabled$truewrite-host"Removing License from user."-ForegroundColorGreen$AssignedLicensesTable=Get-AzureADUser-ObjectId$userToOffboard|Get-AzureADUserLicenseDetail|Select-Object@{n="License";e={$_.SkuPartNumber}},skuidif($AssignedLicensesTable){$body=@{addLicenses=@()removeLicenses=@($AssignedLicensesTable.skuid)}Set-AzureADUserLicense-ObjectId$userToOffboard-AssignedLicenses$body}write-host"Removed licenses:"$AssignedLicensesTableRemove-PSSession$session