The Problem
Stale devices were accumulating in Microsoft Entra with no MDM in place at the time, so the only way to clean them up was manually through the Entra portal. The process was slow, entirely manual, and consumed significant administrator time. Stale device records also represented unnecessary exposure, since a stale device object can still hold access to resources.
What I Built
A PowerShell automation that runs as a scheduled task on a server and removes Entra devices whose last activity falls outside a configurable staleness threshold. It authenticates to Microsoft Graph with certificate-based app-only authentication, so it runs unattended with no stored secrets and no interactive sign-in.
How It Works
- Certificate-based app-only Graph authentication for unattended execution
- Configurable staleness threshold in months, with an optional trust-type scope filter (Entra joined, Entra registered, or hybrid joined)
- Two-pass device discovery: a Graph-side filter on last sign-in date, plus a client-side fallback that catches devices which have never signed in and therefore report a null sign-in date
- Exclusion group support: devices that are direct members of a designated Entra group are completely ignored, never deleted, reported, or counted
- Fail-closed safety design: if exclusion group membership cannot be retrieved, the run stops before enumerating any devices, so a failed protection lookup can never result in deletions
- WhatIf dry-run mode for safe auditing before enabling deletions
- Persistent ledger CSV maintained across runs as a historical audit trail, plus a per-run CSV report
- Separated deletion and ledger-update error handling so a successful delete is never misreported as a failure
- HTML email summary with status banners distinguishing three outcomes: deletions performed, no stale devices found, or run stopped
Why the Exclusion Group
Some locations use shared devices that can legitimately sit inactive for long periods and cross the staleness threshold without being abandoned. Those devices must be available immediately when needed, so they are placed in a protection group and excluded from cleanup entirely.
Impact
- Removes 100 to 2,000 stale device records per run
- Eliminates hours of manual portal cleanup per cycle
- Reduces exposure risk from stale device objects that retain access to resources
- Provides a persistent audit trail of every deletion