Skip to main content
KBY Technologies Logo

Automating Leaver Device Retirement and Autopilot Cleanup in Intune

A practical runbook for retiring leaver devices in Intune, de-registering Autopilot hashes and cleaning up Entra ID device objects with verifiable evidence.

KBY Technologies20 min readIntermediate45 min
Automating Leaver Device Retirement and Autopilot Cleanup in Intune

Advertising disclosure: this article includes partner links. KBY may earn a commission if you sign up or buy through one, at no extra cost to you. How we make money.

Before you begin

  • Basic familiarity with Microsoft Graph PowerShell SDK
  • Working knowledge of Intune device enrolment and Windows Autopilot
  • Understanding of Entra ID roles and device object management

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

A leaver ticket often reaches a junior engineer with one line: close it and confirm the device is clean. The hard part is that a mistake here rarely causes an outage; it shows up months later as an audit question nobody can answer. The steps below retire the device in Intune, remove its Autopilot registration and leave evidence on the ticket for every stage.

#Why disabling the account isn’t enough

When someone leaves KBY Technologies, their corporate laptop does not stop being a security liability just because their Entra ID account gets disabled. If the device is not formally retired in Intune and de-registered from , three things go wrong at once.

First, the device retains cached authentication tokens and can continue to satisfy for a window after the account is disabled, because token expiry and device compliance state do not update instantly.

Second, the Autopilot hardware hash stays bound to the tenant, so if the laptop is redeployed to a new starter without cleanup, it will attempt to re-provision against the leaver’s old deployment profile and, in some tenants, against the leaver’s old group memberships if dynamic group rules were written loosely.

Third, a stale managed device record stays in Intune, which makes device audits unreliable.

This is a lifecycle management gap, not an enrolment gap, and it is exactly the kind of task a junior engineer gets handed in week three: “close this leaver ticket and confirm the device is clean.” Getting it wrong does not usually produce a dramatic outage. It produces a slow-burn audit failure six months later when security asks why a device assigned to someone who left in March is still showing as compliant in April.

#Prerequisites and required permissions

You need the following before touching a single ticket:

  • An Entra ID role of Intune Administrator, which covers the retire/wipe action. This guide no longer deletes the Entra ID device object (see Step 5).
  • Microsoft Graph PowerShell SDK installed, with delegated or app-only consent for the scopes DeviceManagementManagedDevices.Read.All, DeviceManagementManagedDevices.PrivilegedOperations.All (retire and wipe), DeviceManagementServiceConfig.ReadWrite.All (Autopilot), User.Read.All and Device.Read.All. Only read access to Entra ID devices is needed, because nothing here writes to them.
  • The leaver’s device serial number and assigned UPN from the HR offboarding ticket. Never action this from memory or a Teams message. The ticket number is your audit trail.
  • Before either a Retire or a Wipe: the device’s BitLocker recovery key and its local administrator account (Windows LAPS) credentials backed up to your secure store. Both may be lost when a Microsoft Entra joined device is retired, and a wipe erases the device, so take the whichever action you choose.
  • The device’s ownership confirmed from the asset record for that serial number, not only from the ticket.

#Step 1: Confirm the leaver trigger and locate the device record

Pull the managed device record using the UPN from the leaver ticket, not the device name, because device names get renamed and reused.

1Connect-MgGraph -Scopes "DeviceManagementManagedDevices.Read.All","DeviceManagementManagedDevices.PrivilegedOperations.All","DeviceManagementServiceConfig.ReadWrite.All","User.Read.All","Device.Read.All"
2
3$user = Get-MgUser -Filter "userPrincipalName eq 'j.smith@kbytech.com'"
4Get-MgUserManagedDevice -UserId $user.Id | Select-Object DeviceName, SerialNumber, Id, ManagedDeviceOwnerType, ComplianceState, LastSyncDateTime

Expected result: exactly one active managed device, with a LastSyncDateTime recent enough to trust that the retire command will actually reach it. Evidence to capture: paste the device Id and serial number into the leaver ticket before you do anything else. Checkpoint: if two devices return, or the serial number does not match the ticket, stop and reconcile with HR before proceeding, because you are about to issue an irreversible command.

#Step 2: Decide retire, wipe, or full wipe

These are not interchangeable, and choosing wrong either strands corporate data on hardware you never see again or destroys personal data on a BYOD device you had no right to erase.

ScenarioActionEffect
Corporate-owned device, being returned to IT storesWipeFull reset to factory/OOBE state; the Autopilot profile can re-run on next boot while the device is still registered, so keep it powered off in stores until Step 4 has removed the registration
Corporate-owned device, staying with leaver temporarily (notice period)RetireRemoves company data and management, leaves personal data and local OS intact
BYOD / personal device with Company Portal enrolment onlyRetireNever issue a Wipe against a personally owned device

Follow the table: for a standard leaver on a corporate asset being returned to IT stores, Wipe is the default at KBY, and a device going straight to disposal is also wiped before it ships to the recycler.

Retire is used only when a corporate device stays with the leaver for a notice period, or when the device is personally owned.

Before you choose either action, confirm ownership from the asset record for that serial number, not just the ticket, and check it matches the ManagedDeviceOwnerType returned by Step 1; if the asset record, the ticket and Intune disagree, stop and reconcile.

Confirm too that the BitLocker recovery key and local administrator credentials are backed up (see Prerequisites): that backup is a precondition for both Retire and Wipe.

#Step 3: Issue the retire or wipe action via Graph

Do not issue either action until the BitLocker recovery key and local administrator account credentials are backed up and ownership is confirmed against the asset record (Step 2). Both credentials may be lost when a Microsoft Entra joined device is retired; take the same backup before a Wipe.

For Windows devices, a Retire does not remove the Microsoft Entra ID record if the device is registered in Autopilot, and does remove it if the device is Microsoft Entra joined or Microsoft Entra registered and not registered in Autopilot.

Because this guide removes the Autopilot registration only after the action has completed, an Autopilot-registered leaver device keeps its Entra ID record through a Retire, while a non-Autopilot Entra joined device loses it. Removing the Entra ID record is a separate, optional step after the wipe (see Step 5).

1$deviceId = "<managed-device-id-from-step-1>"
2# Retire: device staying with the leaver, or personally owned
3Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices/$deviceId/retire"
4
5# Wipe: corporate device returned to stores or going to disposal; keep no enrolment or user data
6Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices/$deviceId/wipe" `
7  -Body (@{ keepEnrollmentData = $false; keepUserData = $false } | ConvertTo-Json) -ContentType "application/json"

Expected result: no content returned on success (HTTP 204). Evidence to capture: re-query the device immediately afterwards and record the state transition.

Intune device retirement leaver
1$d = Get-MgDeviceManagementManagedDevice -ManagedDeviceId $deviceId
2$d.LastSyncDateTime
3$d.DeviceActionResults | Select-Object ActionName, ActionState, StartDateTime, LastUpdatedDateTime

Microsoft Graph documents deviceActionResults as a read-only collection on the managedDevice resource, with actionState values that include pending, done and failed; check the entry whose ActionName matches your action.

Straight after the call it usually reads pending, but the collection can be empty or unpopulated for some devices and actions, so an empty result proves neither success nor failure. These results can only be read while the managed device record exists. Checkpoint: do not proceed to Step 4 until you have one of two pieces of completion evidence.

Either the device action status shown for that device in the Intune admin centre (its overview page) reports the action as complete, or the deviceActionResults entry, where one is returned, reads done; or, after a Retire, the managed device record no longer exists, because Microsoft says the Retire runs the next time the device checks in and the device might still appear in the admin centre only until then.

A not-found result after a Retire is the expected outcome, not an error: record it, with the time, as the completion evidence. A LastSyncDateTime later than the action’s StartDateTime is not proof on its own; it shows a check-in, not that the action completed. A failed state means stop and investigate.

If the action stays pending, do not delete the device from Intune and do not remove its Autopilot registration, because Microsoft does not document what happens to a queued action whose Intune record is deleted; escalate for physical recovery as described under When leaver cleanup goes wrong. Step 4 runs only once the action is confirmed complete.

It deletes the device from Intune before its Autopilot registration is removed, because Microsoft says a device has to be deleted from Intune before it is deregistered from Windows Autopilot.

#Step 4: Remove the Autopilot hardware hash registration

First, delete the device from Intune. Microsoft’s order is fixed: a device has to be deleted from Intune before it can be deregistered from Windows Autopilot.

Before deleting anything, verify the device’s serial number against both the leaver ticket and the asset record, and have a second engineer repeat that check and record their approval in the ticket; that approval covers both the Intune deletion and the Autopilot removal, and neither proceeds without it.

Then, in the Intune admin centre, go to Devices, then Windows, select the device, confirm its serial number matches the verified one, confirm the retire or wipe shows as complete, and select Delete. If a completed Retire has already removed the record, there is nothing to delete.

Deleting the Intune record cannot be undone, so do it only after the Step 3 checkpoint has passed, never while the action is still pending. Only then remove the Autopilot identity below.

This is the step people forget, and it is the one that causes the device to loop back into a leaver’s old deployment profile if it’s ever re-imaged and reboots into OOBE while still tenant-registered.

1Import-Module Microsoft.Graph.DeviceManagement.Enrollment
2$serial = "<serial-number-from-ticket>"
3$ap = @(Get-MgDeviceManagementWindowsAutopilotDeviceIdentity -All |
4  Where-Object { $_.SerialNumber -eq $serial })
5if ($ap.Count -ne 1) { throw "Expected exactly one Autopilot record for $serial, found $($ap.Count); stop and reconcile" }
6$ap | Select-Object Id, SerialNumber, Model, GroupTag

This lookup is read-only: it retrieves every Autopilot identity with -All and matches the serial number exactly on the client, rather than relying on a server-side -Filter, whose support on this resource is limited. The exact match and count check must pass before anything is removed.

Confirm the returned serial number against the ticket, record the Id (the Autopilot identity id, distinct from the managed device id) in the ticket, then check that Intune no longer holds a managed device record, by the managed device id from Step 1 or by serial number; both lookups must return nothing before you remove that single record.

Before the removal, the script asks you to type the serial number and stops unless it matches; type it from the ticket, not from the screen:

1$byId = Get-MgDeviceManagementManagedDevice -ManagedDeviceId $deviceId -ErrorAction SilentlyContinue
2$bySerial = @(Get-MgDeviceManagementManagedDevice -All | Where-Object { $_.SerialNumber -eq $serial })
3if ($byId -or $bySerial.Count -ne 0) { throw "Intune still holds a managed device record for $serial; delete it from Intune first" }
4$typed = Read-Host "Type the serial number to remove Autopilot record $($ap[0].Id)"
5if ($typed.Trim() -ne $serial) { throw "Typed serial does not match $serial; nothing removed" }
6Remove-MgDeviceManagementWindowsAutopilotDeviceIdentity -WindowsAutopilotDeviceIdentityId $ap[0].Id

Expected result: the serial number no longer appears when the same exact-match lookup is run again. Deregistration might take some time, so if the record is still listed, wait a few minutes and query again rather than repeating the removal.

Evidence to capture: run the same Get-MgDeviceManagementWindowsAutopilotDeviceIdentity -All lookup with the exact serial match a second time and paste the empty result into the ticket. Checkpoint: if the removal call fails, confirm the device has been deleted from Intune, as above, before you try again.

#Step 5: Check the Entra ID device object, and don’t delete it by hand

Don’t delete this device’s Entra ID object by hand. The device is registered with Windows Autopilot (Step 4 removed that registration), and you should avoid manually deleting such a device from Microsoft Entra ID unless a specific scenario requires it: the Autopilot deployment process relies on that object, and deleting it can cause enrolment failures.

System-managed devices such as Autopilot devices can’t be reprovisioned once deleted, deleting a device object also deletes the BitLocker recovery keys stored with it, and there is no way to recover deleted devices or those keys. The object can remain in Entra ID after deregistration.

If the device is Microsoft Entra hybrid joined, delete its computer object from on-premises Active Directory instead, so that it isn’t resynced to Entra ID.

For a leaver device that was never registered with Autopilot, you might also want to remove its record from Entra ID after the action.

If the action was a Retire and the device is Microsoft Entra joined, you won’t need to: the Retire itself removes that record when it runs, which is why Step 3 has you back up the device’s BitLocker recovery key and local administrator account credentials first.

In any other case, if you do remove the record, disable the device for a grace period first and back up any BitLocker recovery key you might need, because deletion can’t be undone.

Record the device’s current Entra ID state with a read-only query:

Get-MgDevice -Filter "displayName eq '<device-name>'" | Select-Object Id, DeviceId, ApproximateLastSignInDateTime

Expected result: for a device that was registered in Autopilot when the action ran, or one that was wiped, the object is still listed; for a device that was not registered in Autopilot and was retired while Microsoft Entra joined or registered, the query returns nothing, because the Retire removed the record. Evidence to capture: paste the query output into the ticket as the expected state, not as a failure.

#Step 6: Close the ticket with evidence

Attach to the leaver ticket: the managed device Id, the Autopilot serial removal confirmation, the Entra ID device query output from Step 5, and the timestamp of each action. This is what an auditor will ask for, and it is what protects you personally if the wrong device ever gets flagged months later.

#One last check before closing the ticket

Before closing the ticket, run a consolidated check:

1Get-MgUserManagedDevice -UserId $user.Id
2Get-MgDeviceManagementWindowsAutopilotDeviceIdentity -All | Where-Object { $_.SerialNumber -eq '<serial-number>' }
3Get-MgDevice -Filter "displayName eq '<device-name>'"

The first two should return empty for a fully retired device. The third follows Step 5: it still returns the Entra ID object of a device that was registered in Autopilot when the action ran, or that was wiped, and Microsoft notes the object can remain after deregistration, so don’t delete it by hand.

For a device that was not registered in Autopilot and was retired while Microsoft Entra joined, it returns nothing, because the Retire removed the record.

If you are working through a batch of leavers, log each serial number and its three query results in a change record rather than trusting memory, because leaver cleanup is exactly the kind of repetitive task where the second or third device of the day gets skipped by mistake.

Automating Leaver Device Retirement and Autopilot Cleanup in Intune architecture diagram 2

#When leaver cleanup goes wrong

The device is offline and the retire command never lands. The action stays pending indefinitely, in the admin centre’s device action status and in DeviceActionResults where an entry is returned, because Intune queues the command and waits for the device to check in; a laptop sitting powered off in a drawer will not action it.

Track pending retires on a dashboard and escalate to physical recovery if a device has not checked in within your offboarding SLA.

While the action is pending, leave the Intune record and the Autopilot registration in place and keep the ticket open; once the device is recovered and powered on, it checks in and takes the queued action, and you continue from the Step 3 checkpoint.

Autopilot removal attempted before the device is deleted from Intune. A device has to be deleted from Intune before it is deregistered from Windows Autopilot, and removing records out of order can result in orphaned records or unrecoverable devices; for a device in an unrecoverable state, contact Microsoft support. Always delete the device from Intune at the start of Step 4, before removing the Autopilot identity.

Entra ID device object deleted by hand. For an Autopilot device, don’t: it can cause enrolment failures, and a system-managed device can’t be reprovisioned once deleted. Deleting the object also deletes the BitLocker recovery keys stored with it. There is no way to recover deleted devices or those keys, so there is no rollback (see What can and can’t be undone).

Dynamic group membership re-adds the device to a corporate profile. If your Autopilot deployment profile assignment is driven by a dynamic device group with a broad rule such as device.enrollmentProfileName -ne null, a device that gets re-registered under a new serial owner can silently inherit the old profile. Review dynamic group rules quarterly, not just at onboarding.

#What can and can’t be undone

A delivered wipe or retire command cannot be reversed: there is no “undo” for data that has already been erased on the device. Your only real controls come before the command: the serial number and UPN check against the ticket (Step 1), and the ownership check and credential backup (Step 2).

A deleted Entra ID device object can’t be restored. Remove-MgDevice deletes devices without prompting, and there is no way to recover deleted devices, or the BitLocker recovery keys stored with them. That is why this guide leaves an Autopilot device’s object in place, and why any BitLocker key you might need is exported first (see Prerequisites).

If you removed an Autopilot hardware hash in error, the device must be re-registered. This requires collecting the hardware hash again (for example with the Get-WindowsAutopilotInfo.ps1 script on the device, or from Configuration Manager) or asking the OEM, reseller or CSP partner to register it again, then reassigning the correct deployment profile. There is no Graph call that restores a removed Autopilot identity from history. Treat this as a fresh registration, and document why in the change record.

#What a closed leaver ticket should show

The end result is a leaver device that is retired or wiped according to ownership type, fully removed from Windows Autopilot registration, with its Entra ID object left in place for Autopilot devices, and documented in the leaver ticket with three pieces of verifiable evidence: the managed device state transition, the empty Autopilot identity query, and the Entra ID device query output.

Retain these against the ticket number for at least one audit cycle. The task is small in scope but unforgiving in sequencing: retire and delete from Intune before Autopilot removal, no manual Entra ID deletion for an Autopilot device, and always verify serial number against the HR ticket before you touch anything.

Treat every step as irreversible until proven otherwise, because most of them are.

#Learning Objectives

After working through this procedure, an engineer should be able to explain why this procedure doesn’t delete an Autopilot device’s Entra ID object by hand: the device can’t be reprovisioned once deleted, and the BitLocker recovery keys stored with the object would be lost with no way to recover them.

A second objective is the ability to justify, from the ownership type recorded on a leaver ticket, whether Retire or Wipe is the correct action, and to articulate the consequence of choosing wrongly: stranded corporate data on returned hardware versus destroyed personal data on a device IT never owned.

A third objective is building the discipline to sequence irreversible actions correctly: retire or wipe first, deletion from Intune second, Autopilot hardware hash removal third, and no manual Entra ID object deletion for an Autopilot device.

A fourth objective is recognising the limits of rollback: knowing that a delivered wipe cannot be undone, that a deleted Entra ID device object can’t be recovered at all, and nor can the BitLocker recovery keys stored with it, and that a mistakenly removed Autopilot identity has no history-based restore and must be treated as a fresh re-registration.

#Worked Example

A leaver ticket arrives for a corporate-owned laptop being returned to IT stores, UPN j.smith@kbytech.com, ticket reference HR-4471.

Following Step 1, the engineer queries the managed device record by UPN and gets exactly one result: device name matches the asset tag on the ticket, serial number matches, and LastSyncDateTime is nine minutes old, which suggests the device checks in regularly, although only the action status in Step 3 proves it received the command. A single matching record is the checkpoint that authorises proceeding.

Because the device is returning to stores rather than staying with the leaver during a notice period, and the ticket does not mark it for disposal, the engineer applies the Step 2 decision table and selects Wipe rather than Retire, since the device will be re-provisioned for a new starter rather than remain with the departing employee.

The engineer issues the wipe call shown in Step 3 with keepEnrollmentData and keepUserData set to false, receives HTTP 204, and re-queries the device: the wipe entry in deviceActionResults reads pending, then done, and the engineer records that done status as the completion evidence.

Only after this is confirmed, and the device has been deleted from Intune, does the engineer move to Autopilot hardware hash removal, matching the serial number from the ticket exactly on the client, confirming exactly one match and recording the identity id before deletion.

A second, empty query against the same serial number confirms de-registration. The Entra ID device object is then queried by display name and, because the laptop is an Autopilot device, left in place. The consolidated check run before closing the ticket returns empty for the Intune and Autopilot queries and shows the Entra ID object, as expected.

The engineer attaches the device Id, the pre- and post-removal Autopilot query outputs and the Entra ID query output to ticket HR-4471 before closing it.

#Practice Exercise

Using a non-production test tenant with a disposable test device object and an Intune Administrator role assigned to your account, reproduce the sequence above end to end and record evidence at each checkpoint rather than trusting memory.

Task 1: query a test managed device by UPN and confirm exactly one result before taking any action; document what you would do if the query returned two devices or a serial number mismatch against a fabricated ticket.

Task 2: using the decision table logic, justify in writing whether a hypothetical BYOD device with Company Portal-only enrolment should ever receive a Wipe command, and state the risk if that boundary is ignored.

Task 3: issue a Retire action against the test device, confirm the HTTP 204 response, and re-query to verify the retire entry in deviceActionResults reads pending, then wait for it to read done, or for the managed device record to disappear, which is the expected result of a completed Retire, before attempting any Intune deletion or Autopilot action.

Task 4: delete the test device from Intune, then remove its Autopilot identity, and record evidence of each. Don’t attempt the removal out of order to see what happens: removing records out of order can result in orphaned records or unrecoverable devices. Task 5: query the test device’s Entra ID object after the Autopilot removal and record that it remains. Don’t delete it: a deleted device can’t be recovered.

Completion criteria: three pieces of evidence per device (state transition, empty Autopilot query, Entra ID query output), a written justification of the Retire-versus-Wipe decision, and the Task 4 evidence that the device was deleted from Intune before its Autopilot identity was removed, all logged against a mock ticket number as if for audit.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01Microsoft's guidance on wiping and retiring devices with Intunelearn.microsoft.com
  2. 02the Windows Autopilot device registration referencelearn.microsoft.com
  3. 03Windows Autopilot registration overviewlearn.microsoft.com
  4. 04How to manage stale devices in Microsoft Entra IDlearn.microsoft.com
  5. 05Wipe devices with Microsoft Intunelearn.microsoft.com
  6. 06Device action: retirelearn.microsoft.com

About this page

Credited to

Dates

Published

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
  • 3 earlier corrections in the log.

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Automating Leaver Device Retirement and Autopilot Cleanup in Intune. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Discover more

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Build practical engineering skills.

Receive new lessons, learning paths, practical exercises and early-career guidance.