Stale Devices in Entra ID and Intune: A Safe Cleanup Guide That Won't Cost You BitLocker Keys
Intune and Entra ID store device records independently — cleaning one system doesn't touch the other. Running a careless bulk delete will permanently destroy BitLocker recovery keys. This guide covers the full safe cleanup sequence: inventory export, Autopilot exclusions, BitLocker backup, disable-then-delete workflow, and PowerShell automation.

Stale Devices in Entra ID and Intune: A Safe Cleanup Guide That Won't Cost You BitLocker Keys
TL;DR: Intune and Entra ID maintain independent device records — cleaning up one does NOT automatically clean the other. Running a careless bulk delete script will permanently destroy BitLocker recovery keys and break Autopilot deployments. This guide walks you through the exact sequence: how to audit stale devices, which ones to skip entirely, how to safely back up BitLocker keys first, and how to automate the whole process without shooting yourself in the foot.
The Problem Every Sysadmin Recognizes
You've been running Microsoft Intune for two or three years. Devices were enrolled, employees left, laptops were replaced, phones were lost. Nobody had a formal hardware offboarding checklist. Now you open Entra ID and see 400 device objects. Intune shows 210. Your actual active fleet is maybe 130 machines.
This isn't a corner case — it's the default state in any organization that hasn't explicitly built a device lifecycle workflow. The sprawl grows silently.
The effects range from annoying to genuinely dangerous:
- Helpdesk confusion: Five objects named "DESKTOP-A3F9K1" for the same user — which one is active?
- Sync overhead: Microsoft Entra Connect performs device writebacks for every registered object. More objects = slower sync cycles against on-premises AD.
- Conditional Access drift: When "managed devices" includes 200 ghost entries, your compliance posture becomes a lie on paper.
- Licensing noise: Intune reports include all enrolled objects, making capacity planning harder.
The dangerous part comes when you finally decide to clean it up. The most common mistake I see: an admin runs a bulk delete script based on ApproximateLastSignInDateTime, skips reading the caveats, and the next morning two employees can't unlock their encrypted drives. BitLocker recovery keys are gone — no recovery possible.
Why This Happens: The Architecture You Need to Understand
Entra ID and Intune Are Two Separate Databases
This is the single most important concept for device cleanup. Intune and Entra ID store device records independently.
When you enable Intune's built-in "Device cleanup rules" and set it to 90 days: Intune removes the record from its own database after 90 days of inactivity. The Entra ID device object stays completely untouched.
The reverse is also true: delete a device from Entra ID via PowerShell, and it will still appear in Intune until the next sync cycle clears the orphaned record.
Most documentation glosses over this. The practical implication: to fully remove a stale device, you need to act on both systems separately, in the right order.
ApproximateLastSignInDateTime Is Not What It Sounds Like
Entra ID tracks device activity through the ApproximateLastSignInDateTime property. Notice the word "approximate" — this is intentional and has real consequences for cleanup scripts.
The timestamp is only updated when:
- A Conditional Access policy requiring a managed or compliant device is evaluated
- A Windows 10/11 Entra joined or Hybrid joined device is active on the network
- An Intune-managed device performs a check-in
The critical part: the timestamp only updates when the delta between old and new value exceeds 14 days (±5-day variance). A laptop that was used yesterday can legitimately show a timestamp from 19 days ago — and that's normal behavior, not a bug.
More dangerously: some active devices have a completely null timestamp. Microsoft documents this explicitly, but many admins miss it. Devices registered before this feature was introduced, or devices that only authenticate against on-premises resources without triggering Conditional Access, may never have a populated timestamp. A script with a condition like $_.ApproximateLastSignInDateTime -le $thresholdDate will treat a null value as January 1, 0001 — effectively matching all devices with null timestamps as "inactive since forever."
This is how active computers end up getting deleted.
The Cleanup Process, Step by Step
Step 1: Full Inventory Export — Baseline Before You Touch Anything
Before any action, export everything. You need Microsoft Graph PowerShell SDK (Microsoft.Graph module).
Connect-MgGraph -Scopes "Device.Read.All"
$devices = Get-MgDevice -All | Select-Object `
AccountEnabled, DeviceId, DisplayName, OperatingSystem, `
OperatingSystemVersion, TrustType, ApproximateLastSignInDateTime, `
IsCompliant, IsManaged
$devices | Export-Csv "$env:USERPROFILE\Desktop\entra-devices-$(Get-Date -f 'yyyyMMdd').csv" `
-NoTypeInformation -Encoding UTF8
Write-Host "Total devices: $($devices.Count)"
Write-Host "Null timestamps: $(($devices | Where-Object { $_.ApproximateLastSignInDateTime -eq $null }).Count)"
Write-Host "Disabled: $(($devices | Where-Object { -not $_.AccountEnabled }).Count)"
Pay attention to TrustType — it tells you how the device is registered:
AzureAD— Entra ID joined (cloud-only, modern workstations)ServerAD— Hybrid Entra ID joined (synced from on-premises AD)Workplace— Entra registered (BYOD, personal phones with work account)
Each type has different cleanup requirements. Hybrid-joined devices especially require a different approach — see the edge cases section.
Step 2: Identify and Exclude Autopilot Devices
This is where cleanups go wrong at enterprise scale. Windows Autopilot devices have an associated ZTDID (Zero Touch Deployment ID) linked to the Entra ID device object. If you delete the Entra ID object while the Autopilot registration still exists:
- User-driven deployments: The device re-enrolls but loses its ZTDID tag, missing its deployment profile assignment
- Self-deploying and pre-provisioning: Deployment fails with a ZTDID mismatch error — a deliberate security mechanism that blocks "impostor" devices from enrolling
Connect-MgGraph -Scopes "DeviceManagementServiceConfig.Read.All"
$autopilotDevices = Get-MgDeviceManagementWindowsAutopilotDeviceIdentity -All |
Select-Object SerialNumber, Model, GroupTag, AzureAdDeviceId
$autopilotDevices | Export-Csv "$env:USERPROFILE\Desktop\autopilot-devices.csv" `
-NoTypeInformation
Write-Host "Autopilot registered devices: $($autopilotDevices.Count)"
Cross-reference this list against your stale devices export. Any device that appears in both lists must be cleaned through the Autopilot portal first (Intune > Devices > Windows > Windows enrollment > Windows Autopilot devices), then removed from Entra ID.
Step 3: Back Up BitLocker Keys — Non-Negotiable
BitLocker recovery keys for Windows devices are stored on the device object in Entra ID. Delete the device object and the keys are gone. There is no recovery path. Microsoft support cannot restore them. This isn't a recoverable mistake.
Connect-MgGraph -Scopes "BitlockerKey.Read.All", "Device.Read.All"
$keyMetadata = Get-MgInformationProtectionBitlockerRecoveryKey -All
$backupKeys = foreach ($meta in $keyMetadata) {
$key = Get-MgInformationProtectionBitlockerRecoveryKey `
-BitlockerRecoveryKeyId $meta.Id -Property "key"
[PSCustomObject]@{
DeviceId = $meta.DeviceId
KeyId = $meta.Id
RecoveryKey = $key.Key
VolumeType = $meta.VolumeType
Created = $meta.CreatedDateTime
}
}
$backupKeys | Export-Csv "$env:USERPROFILE\Desktop\bitlocker-backup-$(Get-Date -f 'yyyyMMdd').csv" `
-NoTypeInformation
Write-Host "BitLocker keys backed up: $($backupKeys.Count)"
Store this file encrypted and in a secure location. It is equivalent to a master key list for every encrypted drive in your organization.
Step 4: Disable First, Delete Later
Never delete a device record directly. The correct workflow is: disable → observe for 14–30 days → delete if no complaints.
Connect-MgGraph -Scopes "Device.ReadWrite.All"
$threshold = (Get-Date).AddDays(-90)
# IMPORTANT: Exclude null timestamps to avoid deleting active devices
$toDisable = Get-MgDevice -All | Where-Object {
$_.ApproximateLastSignInDateTime -ne $null -and
$_.ApproximateLastSignInDateTime -le $threshold -and
$_.AccountEnabled -eq $true -and
$_.TrustType -ne "ServerAD" # Handle Hybrid-joined separately
}
Write-Host "Devices to disable: $($toDisable.Count)"
foreach ($device in $toDisable) {
Update-MgDevice -DeviceId $device.Id -AccountEnabled:$false
Write-Host "Disabled: $($device.DisplayName) | Last seen: $($device.ApproximateLastSignInDateTime)"
}
When a device is disabled in Entra ID:
- Entra joined: User cannot sign in to the device or access M365
- Hybrid joined: User can still sign in locally to the on-prem domain but loses access to cloud resources
- Registered (BYOD): User loses access to resources protected by Conditional Access
Disabling triggers the user or helpdesk to report problems — which is exactly what you want before permanent deletion.
Step 5: Delete After the Grace Period
After 14–30 days of no complaints about disabled devices, proceed with deletion.
$deleteThreshold = (Get-Date).AddDays(-120) # 90 days stale + 30 days disabled
$toDelete = Get-MgDevice -All | Where-Object {
$_.ApproximateLastSignInDateTime -ne $null -and
$_.ApproximateLastSignInDateTime -le $deleteThreshold -and
$_.AccountEnabled -eq $false
}
Write-Host "Devices queued for deletion: $($toDelete.Count)"
Write-Host "This is irreversible. Confirm? (yes/no)"
$confirm = Read-Host
if ($confirm -eq "yes") {
foreach ($device in $toDelete) {
Remove-MgDevice -DeviceId $device.Id
Write-Host "Deleted: $($device.DisplayName)"
}
} else {
Write-Host "Aborted."
}
Note that Remove-MgDevice provides no confirmation prompt — it deletes immediately on execution. The manual confirmation in this script is your only safety net.
Step 6: Configure Intune Device Cleanup Rules
In the Intune admin center: Devices > Device cleanup rules.
Set the threshold between 30 and 270 days (90 days is the industry standard). Important caveats:
- This only removes records from Intune — Entra ID is unaffected
- Removed devices can auto-recover within 180 days if they check in again (designed for extended leaves/sabbaticals)
- Does not apply to Jamf-managed devices
- Does not trigger wipe, retire, or any device-side action
For permanent removal: issue a Retire action on the device first (removes corporate data and MDM enrollment), then let cleanup rules handle the Intune record, then clean Entra ID with the script above.
Edge Cases and Common Mistakes
Mistake 1: Hybrid-Joined Devices — Clean On-Premises First
For devices with TrustType = "ServerAD" (Hybrid Entra ID joined), the cleanup order is the opposite of what most admins expect.
Don't delete from Entra ID first. If you delete the Entra ID object while the on-premises AD computer account still exists, Microsoft Entra Connect will recreate the object in Entra ID at the next sync cycle (default every 30 minutes) — this time in "Pending" state. You'll have it back, but the device will need to re-register.
Correct sequence for Hybrid-joined:
- Disable or delete the computer account in on-premises Active Directory
- Wait for Entra Connect sync, or force it:
Start-ADSyncSyncCycle -PolicyType Delta - Entra ID object updates or disappears automatically
- Clean up from Intune if cleanup rules haven't run yet
For Windows 7/8 Hybrid devices: Entra Connect does NOT synchronize disable/delete actions for these versions. You must manually disable/delete in both on-premises AD AND Entra ID.
Mistake 2: The Null Timestamp Ambush
Microsoft acknowledges that some active devices have a null ApproximateLastSignInDateTime. This includes:
- Devices registered before this feature existed
- Devices that only authenticate on-premises without hitting Conditional Access policies
- Devices with persistent auth issues that prevent timestamp updates
Before deleting any device with a null timestamp, verify activity in Entra ID > Sign-in logs, filtered by Device ID. A device with no cloud sign-ins might be purely on-premises — it's active, just not cloud-active.
Mistake 3: The Intune Auto-Recovery Surprise
Intune cleanup rules are not a one-way door. Devices removed by cleanup rules can reappear within 180 days if they successfully check in and the MDM certificate hasn't expired (certificates are valid for 1 year).
Consequence: you run cleanup in Q4, see 40% reduction in device count. In Q2 next year, the count is creeping back up. This is expected behavior — it's designed for employees returning from extended leave. But if you want permanent removal, Retire the device before relying on cleanup rules.
Mistake 4: Deleting Devices Without Checking Conditional Access Dependencies
Some organizations set up Conditional Access policies that use specific device objects (e.g., "Allow access only from these named devices"). Deleting a device that's in such a policy scope will immediately block the associated user's access.
Before bulk deletion, verify: are any stale devices explicitly referenced in named locations, trusted device lists, or device-based CA policies? This is rare but happens in high-security configurations.
How We Handle This at Evolit
At Evolit, we use Nexma to maintain an authoritative hardware inventory linked to each employee's profile. When an employee leaves, Nexma's offboarding checklist includes a hardware return step that triggers the IT team to perform both Intune retirement and Entra ID cleanup before the offboarding ticket closes. This eliminates the two-month lag between physical device return and digital deregistration — which is typically where ghost device accumulation starts.
For organizations without a dedicated lifecycle tool, a Power Automate flow triggered by an HR system event or an Azure Automation runbook on a weekly schedule can accomplish the same audit trail. The full Nexma device management workflow is documented at nexma.app.
Summary
- Intune cleanup rules and Entra ID are independent systems — one cleanup doesn't trigger the other
- Always filter out null timestamps — active devices without a timestamp will match "inactive" conditions and get incorrectly deleted
- Back up BitLocker keys before any deletion — they are permanently destroyed with the device object
- Autopilot devices require separate deregistration from the Autopilot portal before Entra ID cleanup
- Hybrid-joined devices must be cleaned from on-premises AD first — deleting from Entra ID first causes the object to reappear after the next Entra Connect sync
- Disable → wait → delete — never skip the grace period; it's your only chance to catch false positives before they become permanent data loss