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: Clean up the Entra ID device object and licensing
- 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, three things go wrong at once. First, the device retains cached authentication tokens and can continue to satisfy Conditional Access 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, the stale Entra ID device object and managed device record keep counting against your Autopilot device inventory and Intune licensed device count, which quietly inflates your billing and 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 or Cloud Device Administrator. Retiring a device and deleting a device object are two different privilege boundaries — Intune Administrator covers the retire/wipe action, Cloud Device Administrator covers deleting the Entra ID device object cleanly.
- 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: the device no longer appears in Get-MgDevice queries and drops out of the tenant’s licensed device count on the next Intune sync cycle, typically within a few hours. Evidence to capture: screenshot or export the “before” and “after” device counts for the licence reconciliation report.
#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 object deletion confirmation, 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>'"All three should return empty for a fully retired and cleaned-up device. 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 retire completes. The identity removal call can be rejected while the device is still actively enrolled and syncing normally, because the Autopilot service and the managed device record are loosely coupled but not independent during an active management session. Always sequence Step 3 before Step 4.
Entra ID device object deleted before the Intune retire finishes. This can leave an orphaned managed device entry that reports a missing owner reference on its next scheduled sync, complicating later automation that queries devices by owner. Delete the Entra ID object last, not first.
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.
If you deleted the wrong Entra ID device object, Entra ID retains deleted device objects in a recoverable state for a limited retention window. Restore it with:
1Get-MgDirectoryDeletedItem -DirectoryObjectId "<deleted-object-id>"
2Restore-MgDirectoryDeletedItem -DirectoryObjectId "<deleted-object-id>"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, cleanly deleted from Entra ID, and documented in the leaver ticket with three pieces of verifiable evidence — the managed device state transition, the empty Autopilot identity query, and the empty Entra ID device query. Retain these against the ticket number for at least one audit cycle. The task is small in scope but unforgiving in sequencing: retire before Autopilot removal, Autopilot removal before Entra ID deletion, 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 distinguish the privilege boundary between an Intune Administrator issuing a retire or wipe action and a Cloud Device Administrator deleting the underlying Entra ID device object, and explain why these are treated as separate authorisation points rather than a single offboarding permission.
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, Autopilot hardware hash removal second, Entra ID object deletion last — and to state, without looking it up, why reversing that order produces conflict errors or orphaned records.
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 only be recovered within a limited retention window, 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 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, its object Id captured, and deleted last. The final consolidated three-query check from the Verification section returns empty across all three calls, and the engineer attaches the device Id, the pre- and post-removal Autopilot query outputs, and the Entra ID deletion confirmation 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: attempt Autopilot identity removal deliberately before the retire has completed on a still-checked-in device, and record the resulting conflict behaviour as evidence for the Failure Modes discussion; then repeat the removal correctly once the device state has progressed. Task 5: delete the test Entra ID device object last, then immediately test rollback by retrieving it from Get-MgDirectoryDeletedItem and restoring it with Restore-MgDirectoryDeletedItem — validate success by confirming the object reappears in a standard Get-MgDevice query.
Completion criteria: three pieces of evidence per device (state transition, empty Autopilot query, empty or restored Entra ID query), a written justification of the Retire-versus-Wipe decision, and a documented conflict case from Task 4, 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.
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.
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.
DevOps & Automation
Designing a Verifiable DevOps Workflow with GitHub Actions
A bounded GitHub Actions build-test-deploy workflow, designed with least-privilege permissions, OIDC federation, environment gating, explicit validation evidence and a concrete rollback path.
Security & Operations
Designing a Verifiable Security Workflow with Microsoft Defender
A bounded, five-stage Defender security operations workflow scoped to a test device group, with read-only checks, one reversible response, and a rehearsed rollback path.
Discover more
Graduate Learning
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.