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.

In this lesson
Table of Contents
Table of contents
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
Track this tutorial
Choose your current status and tick each safety check as you complete it. Sign in to sync progress between devices.
Current status
Tutorial stages
- Step 1: Confirm the leaver trigger and locate the device record
- Step 2: Decide retire, wipe, or full wipe
- Step 3: Issue the retire action via Graph
- Step 4: Remove the Autopilot hardware hash registration
- Step 5: Leave the Entra ID device object in place
- Step 6: Close the ticket with evidence
0 of 6 stages complete
Before you apply the change
Confirm these production-safety controls during the tutorial.
#Operational requirement
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 Windows Autopilot
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.PrivilegedOperations.All,DeviceManagementServiceConfig.ReadWrite.AllandDevice.ReadWrite.All. - 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.
- Confirmation that any BitLocker recovery key escrowed against the device has been exported, in case the returned hardware needs re-imaging rather than a corporate wipe.
#Step 1: Confirm the leaver trigger and locate the device record
Action: 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.PrivilegedOperations.All","DeviceManagementServiceConfig.ReadWrite.All","Device.ReadWrite.All"
2
3$user = Get-MgUser -Filter "userPrincipalName eq 'j.smith@kbytech.com'"
4Get-MgDeviceManagementManagedDevice -Filter "userId eq '$($user.Id)'" | Select-Object DeviceName, SerialNumber, Id, ComplianceState, LastSyncDateTimeExpected 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 — 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.
| Scenario | Action | Effect |
|---|---|---|
| Corporate-owned device, being returned to IT stores | Wipe | Full reset to factory/OOBE state, Autopilot profile can re-run on next boot if still registered |
| Corporate-owned device, staying with leaver temporarily (notice period) | Retire | Removes company data and management, leaves personal data and local OS intact |
| BYOD / personal device with Company Portal enrolment only | Retire | Never issue a Wipe against a personally owned device |
For a standard leaver on a corporate asset being returned, Retire is the correct default at KBY unless the ticket explicitly says the device is going straight to disposal, in which case Wipe is used before shipping it to the recycler.
#Step 3: Issue the retire action via Graph
Before you retire a Microsoft Entra joined device, back up its BitLocker recovery key and local administrator account credentials: Microsoft lists both as data that may be lost during a Retire. Microsoft also says a Retire removes the Entra ID record of a Microsoft Entra joined device unless the device is registered in Autopilot (see Step 5). It doesn’t say whether that exception still applies if the Autopilot registration is removed in Step 4 before a pending Retire has run, so back up whether or not the device is registered. None of this has been tested for this guide.
1$deviceId = "<managed-device-id-from-step-1>"
2Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices/$deviceId/retire"Expected result: no content returned on success (HTTP

Get-MgDeviceManagementManagedDevice -DeviceId $deviceId | Select-Object DeviceName, ManagementStateManagementState should move to retirePending. Checkpoint: do not proceed to Step 4 until this reads retirePending or later. Step 4 then 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. In the Intune admin centre, go to Devices, then Windows, select the device, note its serial number, and select Delete. Only then remove the Autopilot identity below. This step has not been tested for this guide.
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.
Get-MgDeviceManagementWindowsAutopilotDeviceIdentity -Filter "contains(serialNumber,'<serial-number>')"Take the returned Id (this is the Autopilot identity id, distinct from the managed device id) and remove it:
Remove-MgDeviceManagementWindowsAutopilotDeviceIdentity -WindowsAutopilotDeviceIdentityId "<autopilot-identity-id>"Expected result: the serial number no longer appears in a subsequent filtered query. Evidence to capture: run the same Get-MgDeviceManagementWindowsAutopilotDeviceIdentity query 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: Leave the Entra ID device object in place
Don’t delete this device’s Entra ID object by hand. The device is registered with Windows Autopilot (Step 4 removed that registration), and Microsoft’s Autopilot guidance is to 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. Microsoft’s stale-device guidance adds that system-managed devices such as Autopilot devices can’t be reprovisioned once deleted, that deleting a device object also deletes the BitLocker recovery keys stored with it, and that there is no way to recover deleted devices or those keys. Microsoft notes the object can remain in Entra ID after deregistration.
If the device is Microsoft Entra hybrid joined, Microsoft says to 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, Microsoft’s Wipe guidance says 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: Microsoft says 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, Microsoft’s stale-device guidance recommends disabling the device for a grace period first and backing up any BitLocker recovery key you might need, because deletion can’t be undone. This guidance has not been tested for this guide.
Record the device’s current Entra ID state with a read-only query:
Get-MgDevice -Filter "displayName eq '<device-name>'" | Select-Object Id, DeviceId, ApproximateLastSignInDateTimeExpected result: for an Autopilot device, the object may still be listed. 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.
#Verification and evidence
Before closing the ticket, run a consolidated check:
1Get-MgDeviceManagementManagedDevice -Filter "userId eq '$($user.Id)'"
2Get-MgDeviceManagementWindowsAutopilotDeviceIdentity -Filter "contains(serialNumber,'<serial-number>')"
3Get-MgDevice -Filter "displayName eq '<device-name>'"The first two should return empty for a fully retired device. For an Autopilot device, the third may still return its Entra ID object; Microsoft notes it can remain after deregistration, so don’t delete it by hand. 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 — leaver cleanup is exactly the kind of repetitive task where the second or third device of the day gets skipped by mistake.

#Failure Modes
The device is offline and the retire command never lands. ManagementState stays at retirePending indefinitely 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.
Autopilot removal attempted before the device is deleted from Intune. Microsoft says a device has to be deleted from Intune before it is deregistered from Windows Autopilot, and that removing records out of order can result in orphaned records or unrecoverable devices; for a device in an unrecoverable state, it says to 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, Microsoft advises against it: 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. Microsoft says there is no way to recover deleted devices or those keys, so there is no rollback (see Rollback).
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.
#Rollback
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 control is the verification checkpoint in Step 1: confirm serial number and UPN against the ticket before issuing the command.
A deleted Entra ID device object can’t be restored. Microsoft says of Remove-MgDevice that it deletes devices without prompting and that 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 either re-running the OA3 tool locally on the device to regenerate the hash, or pulling the hash from OEM-provided CSV via the partner centre, then re-uploading it and 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.
#Operational Summary
Deliverable for this task: 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 as Microsoft advises 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: Microsoft advises against it, 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, confirming the device is online and reachable. This 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 action, receives HTTP 204, and re-queries the device: ManagementState transitions to wipePending, then to a subsequent removed state once the device checks in and completes the reset. Only after this transition is confirmed, and the device has been deleted from Intune, does the engineer move to Autopilot hardware hash removal, filtering by the serial number from the ticket and confirming 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 from the Verification section 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 state reads retirePending before attempting any 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: Microsoft says 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: Microsoft says 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.
Correction, 18 September 2026: earlier versions of this guide told you to delete the leaver device’s Entra ID object by hand with Remove-MgDevice, and said a deleted device object could be restored. Microsoft’s documentation says to avoid deleting an Autopilot device’s Entra ID object, that deleting a device also deletes its BitLocker recovery keys, and that there is no way to recover deleted devices. Those steps now follow it. Later the same day, the guide was corrected again. It used to let you remove the Autopilot registration once the Retire was pending, without deleting the device from Intune first, and a practice task had you try the removal out of order. That contradicted Microsoft’s documentation, which says a device has to be deleted from Intune before it is deregistered from Windows Autopilot; Step 4 now starts with that deletion. Step 5 didn’t say that, for a Microsoft Entra joined device that isn’t registered in Autopilot, Microsoft says a Retire itself removes the Entra ID record. It now does, and Step 3 now tells you to back up the device’s BitLocker recovery key and local administrator account credentials before a Retire, as Microsoft advises. The corrected steps have not been tested in a tenant.
Evidence trail
Sources and verification
Primary documentation and external technical references used in this article.
- 01Microsoft's guidance on wiping and retiring devices with Intunelearn.microsoft.com
- 02the Windows Autopilot device registration referencelearn.microsoft.com
- 03Windows Autopilot registration overviewlearn.microsoft.com
- 04How to manage stale devices in Microsoft Entra IDlearn.microsoft.com
- 05Wipe devices with Microsoft Intunelearn.microsoft.com
- 06Device action: retirelearn.microsoft.com
Related articles
Endpoint and Device Management
A Practical First Workflow for Endpoint Management with Intune
A graduate-level guide to building, scoping and validating one safe Microsoft Intune compliance workflow, with evidence, common mistakes and rollback steps.
Security & Operations
A Practical Security & Operations Recovery Plan for Microsoft Defender
A bounded, evidence-led plan for implementing, validating and safely rolling back a Microsoft Defender exclusion or tamper-protection change across a managed device group.
Security & Operations
Reducing Security & Operations Risk with Microsoft Defender
A technical guide to implementing a bounded Microsoft Defender for Endpoint workflow. Learn how to automate device isolation safely, validate responses, and recover from errors in a non-production environment.
Discover more
Graduate Learning
Ops Playbook
Lexicon Definitions
Learn More About KBY
About KBY
Learn about our mission, editorial standards, and commitment to trusted engineering knowledge.
Why Trust KBY
Explore the processes and policies that ensure our publications are accurate, useful, and responsible.
Newsletter
Get our latest editorial publications, research and practical insights sent directly to your inbox.
Was this useful?
Build practical engineering skills.
Receive new lessons, learning paths, practical exercises and early-career guidance.
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.