---
title: "Automate Employee Offboarding From One HR Status Change"
description: "Build an offboarding workflow in Power Automate that fires on one HR status change: disable accounts, revoke sessions, delegate mail, and lock devices."
canonical: "https://adamtheautomator.com/automate-employee-offboarding/"
---

# Automate Employee Offboarding From One HR Status Change

> Build an offboarding workflow in Power Automate that fires on one HR status change: disable accounts, revoke sessions, delegate mail, and lock devices.

Source: https://adamtheautomator.com/automate-employee-offboarding/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Automate Employee Offboarding From One HR Status Change](https://adamtheautomator.com/wp-content/uploads/publisher/4165d9c85b2b81218b29d8f57bb7fd63/e2543780be9fa68d0b7c3247e23529aaafeca9ff33e6941f8a068cb06eb81a39.webp)

# Automate Employee Offboarding From One HR Status Change

[![](https://secure.gravatar.com/avatar/d0b9d42e21e5622713f8b693aa5c0f9244d5f7dd200ed29b8398f52dee5de337?s=192&d=mm&r=g)Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)24 November 202618 min. read

Categories: [Business Process Automation](/category/business-process-automation/)

Tags:[Power Automate](/tag/power-automate/)[Microsoft Entra](/tag/microsoft-entra/)[Endpoint Management](/tag/endpoint-management/)[Automation](/tag/automation/)

Table of Contents

*   [The Offboarding Automation Stack](#the-offboarding-automation-stack)
*   [Infrastructure Tiers](#infrastructure-tiers)
*   [Make HR the Only Trigger](#make-hr-the-only-trigger)
*   [Prerequisites](#prerequisites)
*   [Setting Up the HR Trigger](#setting-up-the-hr-trigger)
*   [Pass the Trigger Payload to Your Scripts](#pass-the-trigger-payload-to-your-scripts)
*   [Disabling the Identity Provider Account](#disabling-the-identity-provider-account)
*   [Entra ID Account Disablement](#entra-id-account-disablement)
*   [Okta Account Deactivation](#okta-account-deactivation)
*   [Revoking Active Sessions](#revoking-active-sessions)
*   [Entra ID Session Revocation](#entra-id-session-revocation)
*   [Okta Session Revocation](#okta-session-revocation)
*   [Non-SSO Applications and OAuth Tokens](#non-sso-applications-and-oauth-tokens)
*   [Transferring Mailbox and Data Ownership](#transferring-mailbox-and-data-ownership)
*   [Microsoft 365 Mailbox Delegation](#microsoft-365-mailbox-delegation)
*   [OneDrive and SharePoint Ownership Transfer](#onedrive-and-sharepoint-ownership-transfer)
*   [Google Workspace Data Transfer](#google-workspace-data-transfer)
*   [Initiating Device Recovery](#initiating-device-recovery)
*   [Intune Device Lock and Wipe](#intune-device-lock-and-wipe)
*   [Jamf Device Lock for macOS](#jamf-device-lock-for-macos)
*   [Physical Device Collection](#physical-device-collection)
*   [Testing and Logging the Workflow](#testing-and-logging-the-workflow)
*   [Building the Audit Trail](#building-the-audit-trail)
*   [Handling Edge Cases and Failures](#handling-edge-cases-and-failures)
*   [Multiple Accounts or Aliases](#multiple-accounts-or-aliases)
*   [Shared Mailboxes and Service Accounts](#shared-mailboxes-and-service-accounts)
*   [Device Offline or Unreachable](#device-offline-or-unreachable)
*   [API Failures and Retry Logic](#api-failures-and-retry-logic)
*   [Scaling and Monitoring the Workflow](#scaling-and-monitoring-the-workflow)
*   [Extending to SaaS Management Platforms](#extending-to-saas-management-platforms)

If HR emails you when someone resigns, this tutorial is for you. You’ve probably run `Update-MgUser -AccountEnabled:$false` and moved on, while the departing user’s refresh tokens, unclaimed mailbox, unlocked laptop, and third-party OAuth grants waited for you to remember them. Miss one, and that former employee can still open your production Slack workspace a week later.

You’ll build a Power Automate workflow that starts the moment HR marks an employee terminated. It disables the identity provider account and kills live sessions first, then hands the mailbox and files to the manager and locks the laptop through your mobile device management (MDM) platform. Every action lands in an audit record, and you’ll test the whole chain against a throwaway account before it touches a real one.

## The Offboarding Automation Stack

The automation chain spans four infrastructure tiers. Each tier’s API or webhook must be reachable from your orchestration platform (see Tines’ [employee offboarding automation playbook](https://www.tines.com/blog/employee-offboarding-automation-a-playbook-for-it-and-security/)).

### Infrastructure Tiers

| Tier | Component | Deprovisioning Action | API Requirement |
| --- | --- | --- | --- |
| **Trigger Source** | Human resources information system, or HRIS ([BambooHR](https://www.bamboohr.com/), [Workday](https://www.workday.com/), [Rippling](https://www.rippling.com/)) | Detects employee termination | Webhook URL registration or REST API polling endpoint |
| **Identity Layer** | Identity provider, or IdP ([Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/), [Okta](https://www.okta.com/), [Auth0](https://auth0.com/)) | Disables SSO, revokes tokens, removes group memberships | OAuth 2.0 or service principal with [`User.ReadWrite.All`](https://learn.microsoft.com/en-us/graph/permissions-reference) and `User.RevokeSessions.All` |
| **Data Layer** | Email & Storage (Microsoft 365, [Google Workspace](https://workspace.google.com/)) | Delegates mailbox, transfers file ownership | Admin API access with MailboxSettings.ReadWrite and Drive.ReadWrite scopes |
| **Device Layer** | MDM ([Intune](https://learn.microsoft.com/en-us/mem/intune/), [Jamf](https://www.jamf.com/), [Kandji](https://www.kandji.io/)) | Locks device, wipes corporate data, triggers return logistics | Device management API with `DeviceManagementManagedDevices.Read.All`, `DeviceManagementManagedDevices.PrivilegedOperations.All`, and `AuditLog.Read.All` |

### Make HR the Only Trigger

Your HRIS record has to be the only thing that starts offboarding. When a manager announces a departure in an email or a Teams message and nobody updates the HR record, the workflow never fires. Close that gap before you automate anything: have managers file every departure in the HRIS, and have IT forward any departure email it receives to HR instead of disabling the account by hand (see Activepieces’ [employee offboarding automation guide](https://www.activepieces.com/blog/employee-offboarding-automation-a-complete-guide-for-2026.md)).

The diagram below shows how one HR webhook drives the identity, data, and device tiers in order.

![Four-tier offboarding stack](https://adamtheautomator.com/wp-content/uploads/publisher/738db71783314fb00b282fc27c7555d18e5733e9a7be3e9dd235c20eaf390ef1.jpg)

## Prerequisites

If you want to follow along hands-on, you’ll need:

*   **An IdP with API access** like Microsoft Entra ID or Okta, so the workflow can disable accounts and revoke sessions without a portal click.
    
*   **An HRIS that sends webhooks or exposes an API** to fire the trigger.
    
*   **Admin rights in both systems** to create the API clients, [service principals](https://adamtheautomator.com/stop-service-principal-sprawl-entra-id-powershell/), or OAuth apps your stack needs.
    
*   **A workflow orchestration platform** like [Power Automate](https://powerautomate.microsoft.com/) (used in the examples), [n8n](https://n8n.io/), [Zapier](https://zapier.com/), [Tines](https://www.tines.com/), or [Workato](https://www.workato.com/).
    
*   **The [Microsoft Graph PowerShell SDK](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation)**, connected with `Connect-MgGraph` and the scopes in the table above.
    
*   **The [Exchange Online PowerShell module](https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2)** and the [SharePoint Online Management Shell](https://learn.microsoft.com/en-us/powershell/sharepoint/sharepoint-online/connect-sharepoint-online) for the mailbox and OneDrive steps.
    
*   **The [Active Directory module](https://learn.microsoft.com/en-us/powershell/module/activedirectory/)** from Remote Server Administration Tools (RSAT) if you run hybrid Active Directory.
    
*   **[GAM](https://github.com/GAM-team/GAM)** if you run Google Workspace.
    
*   **An MDM platform** (Intune or Jamf) if you lock company-owned devices.
    
*   **[jq](https://jqlang.github.io/jq/)** for parsing JSON responses from the Jamf API.
    

## Setting Up the HR Trigger

The workflow begins when HR changes an employee’s status to “terminated” or sets a termination date. Your HRIS must notify the [orchestration platform](https://learn.microsoft.com/en-us/power-automate/getting-started) the moment the status changes, not in a nightly batch or the next provisioning sync.

If your HRIS supports outbound webhooks, register the orchestration platform’s webhook URL as the notification endpoint. In BambooHR, register the webhook with the [Create Webhook API](https://documentation.bamboohr.com/reference/create-webhook) so the setup is scripted and repeatable. Your API user can only monitor fields it can see, so first check the names your account accepts with the [List Monitor Fields endpoint](https://documentation.bamboohr.com/reference/list-monitor-fields). BambooHR takes your API key as the Basic auth username and any string as the password:

```bash
curl -X POST "https://${BAMBOO_COMPANY}.bamboohr.com/api/v1/webhooks" \
  -u "${BAMBOO_API_KEY}:x" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Offboarding trigger",
    "url": "<your flow webhook URL>",
    "format": "json",
    "events": ["employee_with_fields.updated"],
    "monitorFields": ["employmentHistoryStatus", "terminationDate"],
    "postFields": {
      "workEmail": "employeeEmail",
      "supervisorEmail": "managerEmail",
      "terminationDate": "terminationDate",
      "employeeNumber": "employeeNumber"
    }
  }'
```

`monitorFields` fires the webhook only when the employment status or termination date changes. `postFields` maps each BambooHR field to the name your flow reads: `employeeEmail`, `managerEmail`, `terminationDate`, and `employeeNumber`.

For HR systems without webhook support, poll the HRIS API every 15 minutes for status changes. In Power Automate, create a [**Recurrence** trigger](https://learn.microsoft.com/en-us/power-automate/triggers-introduction) set to 15-minute intervals, then call the HRIS API to retrieve employees whose `employmentStatus` changed to `terminated` since the last poll. Store the last-checked timestamp in a [Dataverse](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/) table or a JSON file in OneDrive so each poll knows where to resume.

Test the webhook by manually updating a test employee’s status in the HRIS, then check the orchestration platform’s run history for the incoming payload. The run history should show the employee’s email, manager email, termination date, and employee number in the trigger output. If the payload is missing any field, the downstream steps cannot execute. Fix the HRIS webhook configuration before moving forward.

### Pass the Trigger Payload to Your Scripts

Run the Microsoft Graph, Exchange Online, and SharePoint Online blocks in this tutorial as [runbooks](https://adamtheautomator.com/azure-runbook/) in an [Azure Automation account](https://learn.microsoft.com/en-us/azure/automation/overview), and start it from the flow with the [Azure Automation connector’s Create job action](https://learn.microsoft.com/en-us/connectors/azureautomation/). Pick the runbook, map the trigger’s employee email, manager email, and employee number to the runbook’s parameters, and turn on **Wait for Job** so the flow waits for the runbook to finish. The Create job action still reports success when the runbook fails, so add a **Condition** after each Create job action that checks `body('<action>')?['properties']?['status']` equals `Completed`, and send the **No** branch to your failure alert.

Each runbook opens with a parameter block instead of hard-coded addresses. It signs in with the Automation account’s managed identity, because an unattended job can’t answer a sign-in prompt:

```powershell
param(
    [Parameter(Mandatory)] [string] $DepartingUserUpn,
    [Parameter(Mandatory)] [string] $ManagerUpn,
    [Parameter(Mandatory)] [string] $EmployeeNumber
)

$ErrorActionPreference = 'Stop'

Connect-MgGraph -Identity
Connect-ExchangeOnline -ManagedIdentity -Organization "company.onmicrosoft.com"
Connect-SPOService -Url "https://company-admin.sharepoint.com" -ManagedIdentity
```

Grant the managed identity the Graph permissions from the tier table before the first run. Microsoft’s [Exchange Online managed identity guide](https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity) covers the Exchange role it also needs. The interactive `Connect-*` lines in the blocks below are for testing a step from your own console. In the runbook, use these sign-ins instead, and replace each hard-coded address with `$DepartingUserUpn` or `$ManagerUpn`.

## Disabling the Identity Provider Account

Once the trigger fires, disable the IdP account first, which blocks SSO to every connected app before the user can react.

### Entra ID Account Disablement

[Connect to Microsoft Graph](https://adamtheautomator.com/entra-automation-users-groups-conditional-access/) with the required scopes, then use the Graph API to set `accountEnabled` to `false`:

```powershell
# Connect to Microsoft Graph (run once per session)
Connect-MgGraph -Scopes "User.ReadWrite.All", "User.RevokeSessions.All", "AuditLog.Read.All", "DeviceManagementManagedDevices.Read.All", "DeviceManagementManagedDevices.PrivilegedOperations.All"

$DepartingUserUpn = "departing.user@company.com"
$userId = (Get-MgUser -Filter "userPrincipalName eq '$DepartingUserUpn'").Id

Update-MgUser -UserId $userId -AccountEnabled:$false
```

The `-AccountEnabled:$false` flag disables the account without deleting it. The user object stays in the directory for the audit trail and for reactivation if HR reverses the termination. The [Update user reference on Microsoft Learn](https://learn.microsoft.com/en-us/graph/api/user-update) defines the accountEnabled property: “`true` if the account is enabled; otherwise, `false`.”

* * *

_**Warning: If [Microsoft Entra Connect](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-azure-ad-connect) syncs your on-premises Active Directory accounts to Entra ID, the next directory sync overwrites a cloud-only disablement. Disable the on-premises account as well.**_

* * *

For hybrid environments, disable the on-premises AD account with [`Disable-ADAccount`](https://learn.microsoft.com/en-us/powershell/module/activedirectory/disable-adaccount):

```powershell
# On-premises AD disablement (run on a domain controller or server with RSAT)
Get-ADUser -Filter "UserPrincipalName -eq '$DepartingUserUpn'" | Disable-ADAccount
```

Verify the account is disabled:

```powershell
Get-MgUser -UserId $userId -Property AccountEnabled | Select-Object AccountEnabled
```

The output should show `AccountEnabled : False`.

### Okta Account Deactivation

Deactivate the user through the Okta API:

```bash
curl -X POST "https://your-domain.okta.com/api/v1/users/$USER_ID/lifecycle/deactivate" \
  -H "Authorization: SSWS ${OKTA_API_TOKEN}" \
  -H "Content-Type: application/json"
```

Replace `$USER_ID` with the Okta user ID and `$OKTA_API_TOKEN` with a valid API token scoped to `okta.users.manage` (see the [Okta deactivate user reference](https://developer.okta.com/docs/reference/api/users/#deactivate-user)).

Deactivation alone does not revoke existing sessions. The user’s active browser sessions and OAuth tokens remain valid until they expire naturally or are explicitly revoked.

## Revoking Active Sessions

A departing employee with an open laptop still connected to your Slack workspace can export every private channel until the session expires, which may take hours or days depending on the application’s timeout policy.

Session revocation forces immediate logout across every active device and application.

### Entra ID Session Revocation

Use the [`Revoke-MgUserSignInSession`](https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.users.actions/revoke-mgusersigninsession) cmdlet:

```powershell
Revoke-MgUserSignInSession -UserId $userId
```

`Revoke-MgUserSignInSession` invalidates all refresh tokens and session cookies issued to the user. The [Microsoft Graph revokeSignInSessions reference](https://learn.microsoft.com/en-us/graph/api/user-revokesigninsessions) states: “This operation prevents access to the organization’s data through applications on the device by requiring the user to sign in again to all applications that they consented to previously, independent of device.” The revocation reaches Microsoft 365 apps and any third-party app that signs in through Entra ID.

Verify session revocation:

```powershell
(Get-MgUser -UserId $userId -Property SignInActivity).SignInActivity.LastSuccessfulSignInDateTime
```

The `LastSuccessfulSignInDateTime` should not advance after revocation. If the timestamp updates after you revoke sessions, the user is still signing in, which means account disablement failed or the user has a secondary credential you missed.

### Okta Session Revocation

Clear all user sessions via the Okta API:

```bash
curl -X DELETE "https://your-domain.okta.com/api/v1/users/$USER_ID/sessions" \
  -H "Authorization: SSWS ${OKTA_API_TOKEN}"
```

Clearing the user’s Okta sessions deletes all active sessions for the user across every Okta-managed application. Okta responds with [HTTP 204 (No Content)](https://developer.okta.com/docs/reference/api/users/#clear-user-sessions) on success.

### Non-SSO Applications and OAuth Tokens

Session revocation through the IdP only affects SSO-connected applications. Applications with local credentials (username and password stored directly in the app) or OAuth-authenticated apps where the user granted access outside the IdP’s control require separate revocation.

For Google Workspace, GAM lists every third-party app the user authorized with their Google account and revokes each grant by client ID:

```bash
# List the OAuth tokens the user granted to third-party apps
gam user departing.user@company.com show tokens

# Revoke one grant, using a client ID from the list above
gam user departing.user@company.com delete token clientid <ClientID>
```

Run the delete once per client ID in the output, then remove the user from any non-SSO application groups.

[BetterCloud’s “Perfect Offboarding” workflow](https://www.bettercloud.com/monitor/anatomy-of-the-perfect-bettercloud-offboarding-workflow/) includes a dedicated OAuth revocation stage that scans and bulk-revokes third-party app authorizations. If you’re not using a SaaS management platform, manually audit and revoke OAuth grants through each application’s admin console.

The flowchart below shows the two revocation paths side by side: IdP session revocation for SSO apps, and per-app token revocation for everything else.

![Session revocation paths](https://adamtheautomator.com/wp-content/uploads/publisher/0db350f64f9eb4e489ded2b5a97326fac5893243b8083944dd627c84e1330075.jpg)

## Transferring Mailbox and Data Ownership

Hand the mailbox and cloud storage to the manager before anything deletes the account, because deletion destroys data the team still needs and may break retention requirements.

### Microsoft 365 Mailbox Delegation

Connect to Exchange Online first, then grant the manager **Full Access** and **Send As** permissions so they can read and respond to emails on behalf of the departing user:

```powershell
# Connect to Exchange Online (run once per session)
Connect-ExchangeOnline

$DepartingUserUpn = "departing.user@company.com"
$managerUpn = "manager@company.com"

Add-MailboxPermission -Identity $DepartingUserUpn -User $managerUpn -AccessRights FullAccess -InheritanceType All
Add-RecipientPermission -Identity $DepartingUserUpn -Trustee $managerUpn -AccessRights SendAs -Confirm:$false
```

The [`Add-MailboxPermission`](https://learn.microsoft.com/en-us/powershell/module/exchange/add-mailboxpermission) cmdlet grants read access to the mailbox. The [`Add-RecipientPermission`](https://learn.microsoft.com/en-us/powershell/module/exchange/add-recipientpermission) cmdlet allows the manager to send emails from the departing user’s address, which is useful for responding to external clients who may not know the employee left.

Use [`Set-Mailbox`](https://learn.microsoft.com/en-us/powershell/module/exchange/set-mailbox) to configure automatic email forwarding so new messages route to the manager:

```powershell
Set-Mailbox -Identity $DepartingUserUpn -ForwardingAddress $managerUpn -DeliverToMailboxAndForward $false
```

The `-DeliverToMailboxAndForward $false` flag forwards all new mail to the manager without retaining a copy in the departing user’s mailbox.

Verify delegation:

```powershell
Get-MailboxPermission -Identity $DepartingUserUpn | Where-Object {$_.User -like "*$managerUpn*"}
```

The output should show the manager’s email with `FullAccess` permissions.

### OneDrive and SharePoint Ownership Transfer

Connect to SharePoint Online first, then transfer ownership to the manager or a designated user:

```powershell
# Connect to SharePoint Online (run once per session)
Connect-SPOService -Url "https://company-admin.sharepoint.com"

$DepartingUserUpn = "departing.user@company.com"
$managerUpn = "manager@company.com"

Set-SPOUser -Site "https://company-my.sharepoint.com/personal/departing_user_company_com" -LoginName $managerUpn -IsSiteCollectionAdmin $true
```

[`Set-SPOUser`](https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/set-spouser) with `-IsSiteCollectionAdmin $true` grants the manager site collection admin rights over the departing user’s OneDrive. The manager can then download critical files or move them to a shared location.

For SharePoint sites where the departing user was the sole owner, add a co-owner before removing the user:

```powershell
$siteUrl = "https://company.sharepoint.com/sites/ProjectAlpha"
Add-SPOUser -Site $siteUrl -LoginName $managerUpn -Group "ProjectAlpha Owners"
Remove-SPOUser -Site $siteUrl -LoginName $DepartingUserUpn
```

[`Add-SPOUser`](https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/add-spouser) puts the manager in the site’s Owners group, and [`Remove-SPOUser`](https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/remove-spouser) takes the departing user out of the site’s user list. Run them in that order: removing the only owner first leaves the site with nobody who can manage its permissions.

Verify ownership transfer by checking the OneDrive site’s admin list:

```powershell
Get-SPOUser -Site "https://company-my.sharepoint.com/personal/departing_user_company_com" -LoginName $managerUpn | Select-Object LoginName, IsSiteAdmin
```

The manager should appear with `IsSiteAdmin : True`.

### Google Workspace Data Transfer

Use the [Data Transfer API](https://support.google.com/a/answer/1247799) to transfer Google Drive ownership and delegate Gmail access:

```bash
# Transfer Drive files to the manager
gam user departing.user@company.com transfer drive manager@company.com

# Delegate Gmail access
gam user departing.user@company.com delegate to manager@company.com
```

The `gam` command-line tool automates Google Workspace admin tasks. The `transfer drive` command moves all files owned by the departing user to the manager’s Drive. The `delegate to` command grants the manager access to the departing user’s Gmail inbox.

By default, Google Workspace keeps a deleted account restorable for 60 days ([retention policy](https://support.google.com/a/answer/33314)). After 60 days, the account and its data are permanently deleted unless you extend the retention period. Finish the Drive transfer and mailbox delegation inside that retention window, and before you wipe any device in the next step, so the manager has the files before the laptop copy is gone.

## Initiating Device Recovery

If the departing employee has a company-owned laptop, tablet, or phone, lock it before they can copy data off it or reach internal systems from it.

### Intune Device Lock and Wipe

Connect to Microsoft Graph with both `DeviceManagementManagedDevices.Read.All` and `DeviceManagementManagedDevices.PrivilegedOperations.All` scopes, then lock the device with [`Get-MgDeviceManagementManagedDevice`](https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.devicemanagement/get-mgdevicemanagementmanageddevice) and [`Lock-MgDeviceManagementManagedDeviceRemote`](https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.devicemanagement/lock-mgdevicemanagementmanageddeviceremote). A lock leaves the data on the device in place, so it is safe to run on every termination:

```powershell
$deviceIds = (Get-MgDeviceManagementManagedDevice -Filter "userPrincipalName eq '$DepartingUserUpn'").Id

foreach ($deviceId in $deviceIds) {
    Lock-MgDeviceManagementManagedDeviceRemote -ManagedDeviceId $deviceId
}
```

`Lock-MgDeviceManagementManagedDeviceRemote` locks the device’s screen, requiring a BitLocker recovery key or the device PIN to unlock.

Verify the lock command was sent by checking the device action results:

```powershell
foreach ($deviceId in $deviceIds) {
    (Get-MgDeviceManagementManagedDevice -ManagedDeviceId $deviceId).DeviceActionResults |
        Select-Object ActionName, ActionState, StartDateTime
}
```

`DeviceActionResults` lists each remote action Intune has queued for the device, with its `ActionState` (`pending`, `done`, `failed`, and so on). If the device is offline, the lock command queues and executes when the device reconnects to the network.

Hold the wipe for high-risk terminations, or for devices that miss the return deadline. A wipe cannot be undone, and running it on every resignation erases any local files the manager or a legal hold review still needs:

```powershell
foreach ($deviceId in $deviceIds) {
    Clear-MgDeviceManagementManagedDevice -ManagedDeviceId $deviceId
}
```

[`Clear-MgDeviceManagementManagedDevice`](https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.devicemanagement/clear-mgdevicemanagementmanageddevice) performs a full factory reset and is for company-owned devices only. For BYOD devices, use [`Invoke-MgRetireDeviceManagementManagedDevice`](https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.devicemanagement/invoke-mgretiredevicemanagementmanageddevice) instead, which removes corporate data while preserving personal files.

### Jamf Device Lock for macOS

Use the [Jamf Pro API](https://developer.jamf.com/jamf-pro/docs/jamf-pro-api-overview) to lock the device. First, get the device’s management ID from the device details endpoint, then send a device lock command:

```bash
# Get the management ID for the device
MANAGEMENT_ID=$(curl -s -X GET "https://your-jamf-instance.jamfcloud.com/api/v4/computers-inventory/$DEVICE_ID" \
  -H "Authorization: Bearer $JAMF_TOKEN" | jq -r '.general.managementId')

# Send the device lock command
curl -X POST "https://your-jamf-instance.jamfcloud.com/api/v2/mdm/commands" \
  -H "Authorization: Bearer $JAMF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "clientData": [{"managementId": "'"$MANAGEMENT_ID"'"}],
    "commandData": {
      "commandType": "DEVICE_LOCK",
      "message": "This device has been locked. Contact IT for assistance.",
      "pin": "123456"
    }
  }'
```

Replace `$DEVICE_ID` with the Jamf device ID and `$JAMF_TOKEN` with a valid API token. The `pin` field sets a temporary unlock code that IT can use to unlock the device after recovery. The `message` field displays a notification on the lock screen.

Jamf responds with HTTP 201 on success. The device locks within seconds if it’s online, or the next time it checks in with Jamf if it’s offline.

### Physical Device Collection

For remote employees, automated prepaid shipping labels streamline device recovery. Platforms like Rippling, [Retriever (Oomnitza)](https://www.oomnitza.com/integration/retriever/), and [Tequipy](https://www.tequipy.com/) dispatch return boxes directly to the employee’s home address with prepaid labels and packing instructions.

If your MDM platform doesn’t offer integrated logistics, create a manual step in your workflow to email the departing employee (or their emergency contact) with return instructions and a shipping label.

For devices that never return, escalate to your legal and finance teams to initiate asset recovery through final paycheck deductions (where legally permitted) or civil claims for unreturned corporate property.

## Testing and Logging the Workflow

Do not deploy offboarding automation to production without testing it against a non-production user account first.

Create a test employee record in your HRIS with a temporary email address (test.user@company.com). Provision the test account in your identity provider, assign it to a few applications, and generate some test files in OneDrive or Google Drive.

Trigger the offboarding workflow by changing the test employee’s status to “terminated” in the HRIS. Monitor each step as it executes:

1.  Verify the HRIS webhook or API poll detected the status change
    
2.  Confirm the IdP account shows `AccountEnabled : False`
    
3.  Check that session revocation invalidated all tokens
    
4.  Validate the manager received mailbox delegation permissions
    
5.  Confirm the test device received the remote lock command
    
6.  Review the audit log entry in SharePoint or your log destination
    

If any step fails, check the orchestration platform’s error logs for the failure reason. Common issues include:

*   The OAuth app or service principal lacks the required API scopes
    
*   The workflow used `samAccountName` instead of `userPrincipalName`
    
*   The workflow exceeded the IdP or email provider’s API rate limit
    
*   [Conditional Access](https://learn.microsoft.com/en-us/entra/identity/conditional-access/) blocked the service principal’s IP address
    

Fix each issue, then re-run the test workflow against a fresh test account. Repeat until the entire workflow executes without errors.

### Building the Audit Trail

Compliance frameworks like [SOC 2](https://www.aicpa-cima.com/topic/audit-assurance/audit-and-assurance-greater-than-soc-2), [ISO 27001](https://www.iso.org/isoiec-27001-information-security.html), and [HIPAA](https://www.hhs.gov/hipaa/) require documented evidence that offboarding actions were executed correctly and on time. Your audit trail must prove when the employee’s status changed, which accounts were disabled, which sessions were revoked, who received delegated access, which devices were locked, and who executed each action.

For Power Automate workflows, capture the run details and write them to a SharePoint list or [Azure Storage Table](https://learn.microsoft.com/en-us/azure/storage/tables/):

```json
{
  "EmployeeEmail": "@{triggerBody()?['employeeEmail']}",
  "TerminationDate": "@{triggerBody()?['terminationDate']}",
  "AccountDisabledAt": "@{variables('AccountDisabledAt')}",
  "SessionsRevokedAt": "@{variables('SessionsRevokedAt')}",
  "MailboxDelegatedTo": "@{variables('ManagerEmail')}",
  "DeviceLockStatus": "@{body('IntuneRemoteLock')?['properties']?['status']}",
  "WorkflowExecutedBy": "Automated",
  "WorkflowRunId": "@{workflow().run.name}"
}
```

Replace `IntuneRemoteLock` with the name of your Azure Automation Create job action that calls the Intune device lock runbook.

Set each variable with `utcNow()` in the step right after its action succeeds, so the record shows when each action ran, not when the record was written.

The Power Automate audit record captures every critical offboarding action with timestamps. Write it to a SharePoint list using the **Create item** action, or send it to [Azure Monitor](https://learn.microsoft.com/en-us/azure/azure-monitor/) for long-term retention and query support.

* * *

_**Pro Tip: Ask your auditor how far back they pull offboarding records, and set log retention to at least that window. Legal hold requirements can push it longer.**_

* * *

Post a summary of the offboarding actions to your IT operations Slack or Teams channel. If a step failed, the missing checkmark tells the on-call admin which action to rerun rather than waiting for an auditor to discover the gap six months later.

## Handling Edge Cases and Failures

Production offboarding workflows encounter edge cases that test environments don’t surface: users with multiple accounts, shared mailboxes with no clear owner, contractors with partial access, devices that never check in (see Hexnode’s [guide to automating employee offboarding across systems](https://www.hexnode.com/blogs/?p=52481)), and API failures during critical sections.

### Multiple Accounts or Aliases

If the departing employee has multiple accounts (admin account, service account, contractor alias), the workflow must disable all of them. Name and email are poor match keys: an admin account like `adm-jsmith` may share neither with the primary mailbox, and it often sits in a different department. Have your HRIS write the employee ID to the `employeeId` attribute on every account the person owns, include that ID in the webhook payload from the HR trigger step, and filter on it. Microsoft Graph [supports `$filter` with `eq` on `employeeId`](https://learn.microsoft.com/en-us/graph/api/resources/user), so one query returns every account tied to that person. Pipe the results straight into the disable step:

```powershell
# $EmployeeNumber is the runbook parameter mapped from the trigger payload
Get-MgUser -Filter "employeeId eq '$EmployeeNumber'" -Property Id, UserPrincipalName |
    ForEach-Object { Update-MgUser -UserId $_.Id -AccountEnabled:$false }
```

An admin account that never got the employee ID written to it won’t come back from this query, so check the result count against the accounts HR expects the person to own.

### Shared Mailboxes and Service Accounts

If the departing employee is the sole owner of a shared mailbox or a service account (noreply@company.com, notifications@company.com), transferring ownership to their manager will break automated workflows that depend on that account. Identify shared mailboxes and service accounts [during onboarding](https://adamtheautomator.com/microsoft-powerautomate/), document the owner and backup owner, and update ownership proactively when an employee leaves.

For shared mailboxes:

```powershell
Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize Unlimited | Get-MailboxPermission -User $DepartingUserUpn
```

Check the `AccessRights` property in the output. If the departing user has permissions on any shared mailbox, add a co-owner before removing them.

### Device Offline or Unreachable

If the device is powered off or disconnected from the network, remote lock commands queue in the MDM platform and execute the next time the device checks in. Until it checks in, the device stays unlocked.

Collect the device in person before telling the employee only when the termination is high-risk (a security incident or an involuntary exit); otherwise the queued lock is enough if the device comes back within the offboarding period.

### API Failures and Retry Logic

Every API in the chain throws transient failures: timeouts, HTTP 429 rate limits, and HTTP 503 outages. Your workflow must retry failed API calls rather than failing the entire offboarding process.

In Power Automate, configure retry policies on each HTTP action. The [Azure Logic Apps error-handling documentation](https://learn.microsoft.com/en-us/azure/logic-apps/error-exception-handling) states: “If the trigger or action’s original request times out or fails, resulting in a 408, 429, or 5xx response, the retry policy specifies that the trigger or action resend the request per policy settings.”

```json
{
  "retryPolicy": {
    "type": "exponential",
    "count": 3,
    "interval": "PT10S",
    "maximumInterval": "PT1M"
  }
}
```

The exponential `retryPolicy` retries the action up to 3 times with exponential backoff, starting at 10 seconds and capping at 1 minute. If the action still fails after 3 retries, the action is marked as failed and later steps are skipped unless you configure the next step’s **Configure run after** settings as described in the note below.

* * *

_**Note: Configure the next step’s Configure run after settings to include has failed and has timed out, otherwise later steps are skipped when an action fails. By default, Power Automate only runs the next step if the previous one succeeded.**_

* * *

For critical steps like account disablement, alert the IT team if the action fails after retries:

```text
CRITICAL: Failed to disable account for departing.user@company.com after 3 retries.

Error: HTTP 503 Service Unavailable
Action: Manually disable the account in the Entra ID admin portal.
Workflow Run ID: [link to run history]
```

Send that alert to whoever is on call so they can disable the account by hand.

## Scaling and Monitoring the Workflow

Track these metrics. The targets are illustrative starting points, so tune them to your own termination volume and risk tolerance:

| Metric | Target | Why It Matters |
| --- | --- | --- |
| **Time from HR status change to account disable** | < 5 minutes | The former employee can still sign in until this step runs |
| **Workflow success rate** | \> 95% | Frequent failures indicate API permission issues or brittle error handling |
| **Average offboarding duration (end-to-end)** | < 30 minutes | Faster offboarding reduces manual IT intervention and audit gaps |
| **Device recovery completion rate** | \> 90% | Unreturned devices are a financial loss and a security risk |
| **Audit log completeness** | 100% | Missing audit records fail compliance audits |

Pull these metrics from your orchestration platform’s analytics dashboard or export run history data to [Power BI](https://powerbi.microsoft.com/), [Grafana](https://grafana.com/), or [Splunk](https://www.splunk.com/) for visualization.

If your workflow’s success rate drops below 95%, investigate the most frequent failure causes. Common culprits include API token expiration, overly aggressive rate limits, and IdP schema changes that break attribute mappings.

If device recovery completion falls below 90%, escalate the logistics process. Email the employee again, offer expedited shipping, or engage external asset recovery services for high-value devices.

### Extending to SaaS Management Platforms

Apps an employee signed up for with a local password or a personal OAuth grant sit outside the IdP’s SSO control, so disabling the IdP account never reaches them.

SaaS management platforms like [BetterCloud](https://www.bettercloud.com/), [Lumos](https://www.lumos.com/), [Nudge Security](https://www.nudgesecurity.com/), and [Torii](https://www.toriihq.com/) extend offboarding automation to non-SSO applications by:

1.  Discovering shadow IT and unmanaged accounts via OAuth grant auditing
    
2.  Revoking OAuth tokens granted to third-party applications (Trello, Notion, ChatGPT, Canva)
    
3.  Transferring ownership of business-critical resources (Jira projects, Confluence spaces, Slack channels)
    

Call the platform from the end of your Power Automate flow instead of running it as a second, separate offboarding. Your flow keeps the IdP, mailbox, and device steps, while the platform handles only the apps your IdP never controlled. Two independent workflows working the same termination can each assume the other revoked an app.

Add the stages in the order this tutorial built them: the HR trigger and IdP account disablement first, validated in production, then session revocation, mailbox delegation, device recovery, and the [SaaS management platform](https://www.bettercloud.com/saas-management/) hand-off. Before each new stage goes live, rerun the test account through the whole chain and confirm the audit record holds a timestamp for every step that ran. A blank field means the new stage broke something upstream.

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fautomate-employee-offboarding%2F&text=Automate%20Employee%20Offboarding%20From%20One%20HR%20Status%20Change)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fautomate-employee-offboarding%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fautomate-employee-offboarding%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/publisher/4165d9c85b2b81b6b0e0cc29388883e7/81f5f4ced3359a4de033c21b8c387a3d1b7da4504939a6b068fbf04dfa9681f0.webp)

### [Automate Contract Renewal Reminders Before They Auto-Renew](/automate-contract-renewal-reminders/)

Build a Power Automate renewal calendar that warns contract owners 90, 30, and 7 days before the notice deadline and escalates when nobody answers.

![](https://adamtheautomator.com/wp-content/uploads/publisher/3ec5d9c85b2b812d96aaea8aa772a1e7/1406d20d337f1ef7937f468af2feb30f4a99e0ac228d4316500d0d14b5868bd7.png)

### [Power Automate: Streamline Invoice Approvals in Teams](/power-automate-invoice-approvals-teams/)

Build a Power Automate flow that routes invoice approvals through Teams, stores documents in SharePoint, and preserves an audit trail.

![](https://adamtheautomator.com/wp-content/uploads/publisher/3ec5d9c85b2b81b19274c73baf4c55f3/98f4af306255355a84e7293721f7eba0ae787ac2055f021d4fddbae4f4385bee.webp)

### [Automate Expense Report Approvals with Power Automate](/power-automate-expense-approval-flow/)

Build a Power Automate approval flow on a SharePoint list that routes expense reports, closes the self-trigger loop, and exports approved spend for finance.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
