Skip to main content
KBY Technologies Logo
Graduate Track

Automating Stale Device Cleanup in Intune and Entra ID

A hands-on runbook for junior engineers to identify, retire and remove stale Intune and Entra ID devices without breaking Conditional Access.

Elliot Ward 15 July 20269 min read Intermediate 45 min labEndpoint and Device Management

Mission brief

What you will achieve

Complete a production-safe implementation and leave with verification and rollback evidence.

Practical steps

7 guided stages

Follow these in order as your working checklist.

Time to set aside

About 45 minutes

Includes configuration, validation and rollback checks.

Tutorial navigation
Production note
Validate permissions, test changes in a non-production scope, record the previous state, and retain a rollback path before applying operational steps.

Before you begin

  • Microsoft Graph PowerShell SDK basics
  • Intune device management fundamentals
  • Entra ID device object concepts

#Operational requirement

You will inherit this task within your first few months on any Intune-managed estate. The device count in Entra ID and Intune drifts well past the number of actual employees, and nobody trusts the reporting any more. Laptops get reimaged and re-enrol as brand-new objects. Loaner pool devices get wiped and returned to stock, but the old Intune record keeps reporting non-compliant forever. Someone’s personal phone gets factory reset and the orphaned managed device object keeps consuming a licence seat.

None of this is cosmetic. Stale objects inflate Intune licence consumption against your Microsoft 365 allocation, pollute dynamic device groups used for Conditional Access exclusions, and create duplicate hostname records that make helpdesk troubleshooting genuinely dangerous. A technician retiring “the laptop assigned to Sarah Jones” from a list of three identically named stale objects has a real chance of wiping the wrong one. A Conditional Access policy will also happily honour a stale-but-technically-compliant object from eighteen months ago, giving a decommissioned machine continued access to Exchange Online and SharePoint until someone notices.

This is the runbook you follow. It covers identifying stale devices, choosing between Retire, Wipe and Delete, automating the recurring pass, and handling the Entra ID device object and the Windows Autopilot registration separately, because cleaning one layer does not clean the others.

#Prerequisites and permissions

Confirm you hold the Intune Administrator or a custom RBAC role with device delete and retire rights, plus Cloud Device Administrator in Entra ID for object removal. You need the Microsoft.Graph PowerShell SDK installed and consented scopes for DeviceManagementManagedDevices.ReadWrite.All, Device.ReadWrite.All and Directory.ReadWrite.All. Raise a change ticket before you run anything against production devices; this is not a task you run informally against live tenant data. Pull your BitLocker key escrow procedure and confirm who owns recovery key retrieval before you touch any Entra device object tied to an encrypted machine.

#Step 1 — Define what “stale” actually means for your estate

Do not pick an arbitrary number. Pull your check-in cadence data first. A typical corporate laptop syncs every eight hours when powered on; a device that hasn’t synced in sixty days is either dead, decommissioned, or belongs to someone on long-term leave. Kiosk devices, digital signage and low-power field tablets often check in weekly by design — apply a longer threshold or exclude them entirely using a device category tag.

Before you write a single query, tag your exceptions. In the Intune admin centre, go to Devices > All devices, assign a device category of DoNotClean to kiosk and loaner pool hardware, or set an extension attribute on the corresponding Entra device object. Your script and the built-in clean-up rule both need to respect this exclusion.

#Step 2 — Query stale devices with Microsoft Graph PowerShell

Connect with the scopes you need and pull the managed device list, filtering client-side on lastSyncDateTime because the managed devices endpoint does not filter reliably on date server-side across all tenant configurations.

1Connect-MgGraph -Scopes "DeviceManagementManagedDevices.Read.All","Device.Read.All"
2
3$threshold = (Get-Date).AddDays(-60)
4
5$devices = Get-MgDeviceManagementManagedDevice -All
6
7$stale = $devices | Where-Object {
8    $_.LastSyncDateTime -lt $threshold -and
9    $_.DeviceCategoryDisplayName -ne "DoNotClean"
10}
11
12$stale | Select-Object DeviceName, UserPrincipalName, LastSyncDateTime, ManagedDeviceOwnerType |
13    Export-Csv .stale-devices-$(Get-Date -Format yyyyMMdd).csv -NoTypeInformation

Get that CSV reviewed before you touch anything. This is your change record. Attach it to the ticket, not just the raw script output.

#Step 3 — Decide: Retire, Wipe or Delete

ActionEffect on deviceEffect on Intune recordReversibleUse case
RetireRemoves managed apps, profiles, VPN and Wi-Fi config; keeps personal data intactRemoved after next check-inNo, but no data lossUser keeps device — BYOD offboarding, role change
WipeFactory reset, all data destroyedRemoved once wipe confirmsNo — irreversibleCorporate device leaving custody, lost or stolen
Delete (record only)None, device untouched physicallyRemoved from console immediatelyDevice re-enrols and reappears with a new object IDCleaning a duplicate where the device already re-enrolled cleanly

The trap most juniors fall into is treating Delete as the safe default because it “just removes the entry.” It does not touch the device. If the device is still active and managed, it checks in on schedule and creates a brand-new managed device object — you have just generated the exact duplicate problem you were asked to fix.

#Step 4 — Execute the retirement action

For a confirmed decommissioned device, retire it first, then let the record clear naturally, or force removal once retirement is confirmed complete.

1# Retire a specific managed device
2$deviceId = "11111111-2222-3333-4444-555555555555"
3Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices/$deviceId/retire"
4
5# Confirm state, then remove the stale record once retirement completes
6Remove-MgDeviceManagementManagedDevice -ManagedDeviceId $deviceId

Never batch a Wipe command across a CSV without per-device manual sign-off. Retire and Delete are safe to script in bulk once verified against your exclusion list. Wipe is not — full stop.

#Step 5 — Clean up the Entra ID device object separately

Removing the Intune managed device record does not remove the corresponding Entra ID device object. That object still drives dynamic group membership and Conditional Access device-based conditions.

1Connect-MgGraph -Scopes "Device.ReadWrite.All"
2
3$entraDevice = Get-MgDevice -Filter "displayName eq 'LAPTOP-4471'"
4Remove-MgDevice -DeviceId $entraDevice.Id

Do this only after confirming the Intune retirement or deletion succeeded, and only after any escrowed BitLocker recovery keys tied to that object have already been retrieved and archived per your key management procedure.

#Step 6 — Automate the recurring pass with the built-in clean-up rule

In the Intune admin centre, go to Devices > Device clean-up rules and configure Delete devices that haven't checked in for [X] days, where X sits between 30 and 270. Ninety days is a defensible starting point for a mixed corporate and BYOD estate — set it conservatively on day one.

Understand exactly what this rule does before you enable it. It removes the Intune managed device record only. It does not delete the Entra ID device object and it does not touch the Windows Autopilot registration. Treat it as stage one of a three-stage cleanup, not the whole job.

#Step 7 — Handle the Autopilot registration as its own layer

If a physical device is leaving the estate entirely, go to Devices > Enrollment > Windows enrollment > Devices and deregister the hardware hash. Skip this and a reimaged unit that gets redeployed will still attempt Autopilot provisioning against the old profile assignment during OOBE — sometimes pulling the previous user’s profile, or hitting an enrolment restriction limit that no longer applies but is still counting the old hash.

#Monitoring and change control

Run the stale device query as a scheduled task on a monthly cadence and route the CSV output to a shared location the service desk can audit. Log every Retire, Wipe and Delete action against the change ticket number in your ticketing system, not just in the script’s own transcript. If your organisation runs a licence dashboard against Microsoft 365 usage, add a monthly checkpoint comparing managed device count against licensed seats — a sudden jump between checkpoints is your early warning that cleanup has lapsed or that a bulk enrolment event has occurred that nobody flagged.

#Verification

Confirm the total managed device count in Intune before and after the pass and reconcile against your Microsoft 365 licence usage report. Check the Intune audit log — filter by category Device and activity Delete or Retire — to confirm each action matches your change ticket line by line. Check Entra ID sign-in logs for any user whose device was cleaned, to confirm they haven’t been unexpectedly blocked by a Conditional Access policy that referenced the deleted device object. Dynamic group membership updates are not instant — allow up to twenty-four hours before verifying that cleaned devices have actually dropped out of Conditional Access exclusion or targeting groups.

#Common Traps

  • Deleting the Intune record before retiring an active device. The device checks in on its normal schedule and creates a brand-new duplicate object with a new device ID — the exact problem you were asked to fix.
  • Deleting the Entra device object on a hybrid-joined, co-managed device. This breaks the Configuration Manager pivot and the device shows non-compliant in the CM console despite being healthy, usually surfacing as a conflicting record on the next hybrid sync.
  • Deleting a device object before retrieving an escrowed BitLocker recovery key. The key metadata is tombstoned for roughly thirty days but retrieval becomes materially harder once the linking device object is gone.
  • Setting the clean-up rule threshold too aggressively against low check-in-frequency kiosk hardware. Users see unexpected “organisation data will be removed” prompts on devices that were never actually abandoned.
  • Forgetting the Autopilot deregistration step. A redeployed device pulls the previous user’s deployment profile at OOBE, or an enrolment restriction limit blocks the new assignment because the old hash is still counted against it.

#Rollback

Entra ID retains deleted device objects in a recoverable state for roughly thirty days. If you delete the wrong object, restore it directly through Graph:

1Connect-MgGraph -Scopes "Directory.ReadWrite.All"
2$deletedId = "11111111-2222-3333-4444-555555555555"
3Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/directory/deletedItems/$deletedId/restore"

There is no equivalent restore for a deleted Intune managed device record. The practical remedy is to have the affected user open Company Portal and re-trigger enrolment, which regenerates management with a new device ID and briefly resets the compliance grace period, but causes no data loss because policies and apps redeploy automatically. A Wipe action has no rollback path whatsoever — this is exactly why Wipe must be confirmed per-device against a signed change ticket and never run as part of a scripted batch. If a clean-up rule threshold turns out too aggressive, reduce or disable it immediately in Devices > Device clean-up rules. It only prevents future deletions and cannot un-delete records already removed, so start conservative rather than correcting after the fact.

#Operational Summary

Stale device cleanup is not a one-off script. It is three separate lifecycle layers — the Intune managed device, the Entra ID device object, and the Autopilot registration — that must be cleaned independently and in the correct order. Confirm and tag exclusions first. Retire before deleting. Remove the Entra object only after any recovery data is secured. Deregister Autopilot hashes for hardware actually leaving the estate. Let the built-in clean-up rule handle only the recurring Intune-layer pass, with a threshold you have validated against your real check-in cadence, not a number picked from a blog post. Get this sequence wrong and you resurrect duplicate objects, break Conditional Access assumptions, or destroy user data with no way back. Get it right and it becomes a quiet, unremarkable monthly job — which is exactly what good device lifecycle management is supposed to feel like.

Reader Support: KBY Technologies is an independent engineering editorial. We may earn a commission from affiliate links when you purchase infrastructure, software, or tools through our recommendations. This helps fund our research and labs.

Advanced suggested reading

Ready to go deeper?

These articles come from KBY’s senior engineering editorial. Expect denser architecture, fewer introductory explanations and deeper production trade-offs.

Leaving Graduate Track
Reader Interaction

Comments

Add a thoughtful note on Automating Stale Device Cleanup in Intune and Entra ID. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Loading anti-spam check...

Continue the track

Related Graduate tutorials

View learning path