Getty Images

Automate Microsoft 365 user offboarding with PowerShell

Automation is a good way for admins to handle all the tasks associated with removing a user from the organization's tenant in Microsoft's cloud-based productivity platform.

Properly offboarding a user from Microsoft 365 requires attention to detail. By automating the process with PowerShell, admins can stick to best practices, avoid common mistakes and execute changes quickly.

The process to deprovision a user is comprehensive and can take a long time to do properly when done manually. When making changes in multiple admin portals, there's always a chance of missing a step. PowerShell is an excellent tool to handle Microsoft 365 user offboarding due to its speed, flexibility and integration capabilities. Once you have tested an offboarding script tailored for your environment, then you can reuse it with confidence without worrying if a key step will be missed or making a mistake. PowerShell's logging and reporting capabilities further strengthen accountability and audit trails.

What is Microsoft 365 user offboarding?

When offboarding an employee, the IT department needs to deprovision the user from the company's Microsoft 365 tenant. The most typical reason is when an employee leaves the company. Offboarding often includes the following:

  • Revoking access to various Microsoft 365 services.
  • Transferring ownership of files and data.
  • Disabling user accounts.

It is crucial to have a proper offboarding method to ensure the security of the organization's data. Failure to do so may result in unauthorized access to files, potential breaches, loss of information and noncompliance with regulations.

How can PowerShell assist with Microsoft 365 user offboarding?

User offboarding is the type of task that doesn't vary much, making it ideal to automate with a PowerShell script. There are many benefits to using automation when performing admin tasks in Microsoft 365, including the following:

  • Consistency. Automation standardizes offboarding so each user goes through the same checklist of tasks.
  • Time efficiency. Automation performs multiple deprovisioning tasks faster than manual methods.
  • Reduced errors. A tested script follows a set procedure to minimize the chance of mistakes, particularly one that involves many steps.
  • Security. Automated offboarding revokes access privileges promptly to reduce unauthorized access risks.
  • Documentation. Automation keeps detailed offboarding records, which is beneficial for audits and helps IT team members understand the processes followed when a user leaves.
  • Resource reassignment. Automation assists in transferring tasks, files and resources from the departing user to other team members.
  • Notifications. A script can issue alerts to keep relevant parties informed about the stages of the offboarding process.
  • Compliance. Automation removes access to sensitive data and systems when a user leaves to maintain regulatory compliance.

Performing user deprovisioning with PowerShell adds speed and efficiency to a process that, in some cases, might require a fast resolution.

Microsoft has a feature called Entra Lifecycle Workflows, which can do some of this offboarding automation work. To use it, the organization must pay for Entra ID Governance and also subscribe to Microsoft Entra ID P1 or P2 at a cost of $6 or $9 per user per month, respectively. Entra Lifecycle Workflows is limited in its functionality and requires additional work to match the integration capabilities in PowerShell.

How does automation help IT avoid deprovisioning errors?

As part of my work, I review many Microsoft 365 tenants, and it's not uncommon to find active accounts for former employees with licenses assigned and elevated access rights.

A tested PowerShell script helps standardize all the offboarding steps, reducing the likelihood of errors or oversights. You can trigger the offboarding when a user confirms their departure to prevent any delay with access removal.

A comprehensive script ensures the complete removal of all access rights by scanning every service accessible to the departing user.

PowerShell can generate a detailed log of every action in the offboarding process, including the date and time, for review and auditing purposes.

Automation also manages the transfer or backup of essential files to prevent data loss.

Lastly, a PowerShell script can revoke and reallocate licenses to prevent unattended licenses, a common oversight in manual processes.

Key areas of focus when offboarding Microsoft 365 users

When offboarding users, it is crucial to concentrate on several key areas beyond the technical aspects to ensure the process is thorough, secure and efficient:

  1. Access revocation. The primary emphasis should be to revoke the user's access to all systems, applications and data. This includes email accounts, file-sharing systems, CRM systems and other software or platforms.
  2. Data security. Secure any sensitive data accessible by the user. This might involve transferring files to another employee, deleting personal data per privacy regulations or changing shared passwords.
  3. Communication. Notify all relevant parties, internally and externally, about the user's departure. This can include team members, clients, vendors or other stakeholders.
  4. Asset retrieval. Recover all physical and digital assets. Physical assets include any company-owned hardware, such as laptops, phones or keycards. Digital assets include software licenses, cloud storage and digital keys.
  5. Documentation. Document every step of the offboarding process. It can be necessary for future audits to understand actions taken and ensure a consistent method.

When offboarding users within Microsoft 365, you should address the following:

  1. License management. Remove the user's licenses to save costs or make them available to another user.
  2. Email forwarding. Consider setting up a forward on the departing user's email account to send email to a manager or replacement to ensure continuity.
  3. Archiving data. Store the user's mailbox, Microsoft Teams data and other essential information for record-keeping and regulatory compliance needs.
  4. Device management. Use Microsoft 365's device management capabilities or Microsoft Intune to remove company data from the user's devices.

By focusing on these areas, you can help ensure a smooth offboarding process that maintains the security and integrity of your systems and data.

How to set up and use PowerShell to manage user offboarding

You can create a PowerShell script to follow best practices when offboarding a user account in Microsoft 365. As an example, the script could include the following tasks:

  • Disable the user's sign-in access to all Microsoft 365 services to prevent unauthorized use.
  • Convert the mailbox to a shared one for a handover period, set up automatic replies or email forwarding, or export the mailbox content for archiving.
  • Identify and preserve necessary data from the user's account.
  • Remove the user's Microsoft 365 license.
  • Wipe corporate data from the user's devices.
  • Remove the user from Microsoft 365 Groups, Microsoft Teams and distribution lists.

Enterprises might have a lengthier list of offboarding requirements. The script should also document every step, including successes, failures and scripted actions that were not necessary to execute.

To start, Microsoft recommends using the Microsoft Graph PowerShell SDK where possible. For this example, the assumption is that you use Microsoft Entra ID -- formerly Azure Active Directory -- app registration to connect using application permissions, not delegated permissions, within PowerShell. This setup enables you to use a third-party application to initiate the offboarding process and then call the code to perform the cleanup work in Microsoft Entra ID.

First, connect and authenticate to the Microsoft Graph API with PowerShell:

Connect-MgGraph `
-ClientId "a0513d31-4515-9729-bfeccbb3273c" `
     -TenantId "4510da24-48d3-837d-d68966409eb2" `
     -CertificateThumbprint "0C21DA5EDDDFF9802AC0975C96AFF1DA" `

Once connected, find and store the user's details:

# Get the user to offboard
$userPrincipalName = "[email protected]"
$user = Get-MgUser -UserId $userPrincipalName

Next, execute the tasks for offboarding. Start with disabling the account, and then remove all roles and licenses assigned to the user:

# Block the user from signing in
Update-MgUser -UserId $userPrincipalName -AccountEnabled:$false
# Remove all roles assigned to the user
$roles = Get-MgDirectoryRole
foreach($role in $roles)
$members = Get-MgDirectoryRoleMember -DirectoryRoleId $role.Id
     foreach($member in $members)
          if($member.Id -eq $user.Id)
              Remove-MgDirectoryRoleMemberByRef `
                   -DirectoryRoleId $role.Id -DirectoryObjectId $user.Id
# Remove the user's license
$licenses = Get-MgUserLicenseDetail -UserId $user.Id
foreach($license in $licenses)
     Set-MgUserLicense `
              -UserId $user.Id `
              -AddLicenses @() `
              -RemoveLicenses @($license.SkuId)

Another crucial step is the audit record, which could be as simple as a regular PowerShell transcript or as complex as a custom-formatted document.

The transcript approach is straightforward and captures executed commands. The code can save the actions into a file, and the NoClobber parameter prevents overwriting of the file. To use it, add the first line to the start of your script and the second line at the end:

Start-Transcript -Path "C:\Transcripts\Report.txt" -NoClobber

After you execute the script with the transcript commands, the system generates a file with a detailed output of all executed operations.

Every organization is different and uses different services. These examples don't encompass every facet of Microsoft 365. For example, you might need to store the user's OneDrive for Business files or content left in SharePoint Online. Evaluate any offboarding scripts in a controlled environment before executing them in a production setting.

Liam Cleary is founder and owner of SharePlicity, a technology consulting company that helps organizations with internal and external collaboration, document and records management, business process automation, automation tool deployment, and security controls and protection. Cleary's areas of expertise include security on the Microsoft 365 and Azure platforms, PowerShell automation and IT administration. Cleary is a Microsoft MVP and a Microsoft Certified Trainer.

Dig Deeper on Microsoft messaging and collaboration

Cloud Computing
Enterprise Desktop
Virtual Desktop