Automating Stale Device Cleanup in Microsoft Entra ID

In an earlier post, we’ve explored managing stale devices in Entra ID. While removing old devices manually lends control, it’s not scalable, especially in hybrid or large-scale deployments. Automating cleanup of stale devices using PowerShell and Microsoft Graph is therefore more practical.

Why automate stale-device cleanup?

  1. Security exposure: Devices no longer in use but still trusted can be hijacked if compromised.
  2. Licensing & cost efficiency: Cleanup ensures you’re not paying for defunct device objects.
  3. Audit readiness: Streamlining device lifecycle supports compliance and clean reports.

Detecting stale devices

  • Define stale devices based on last logon timestamp or noncompliance status:
  • Devices not used in the past 90 days.
  • Devices marked “noncompliant” due to policy.

You can gather this data with Microsoft Graph:

Connect-MgGraph –Scopes “Device.Read.All”,”Directory.Read.All”
$threshold = (Get-Date).AddDays(-90)
$stale = Get-MgDevice -Filter “approximateLastLogonTimestamp lt $($threshold.ToFileTimeUtc())”

Automating removal with PowerShell

Once stale devices are identified, automate deletion:

foreach ($device in $stale) {
# Optional backup: export to CSV
# Remove via Graph
Remove-MgDevice -DeviceId $device.Id
Write-Host “Deleted stale device: $($device.DisplayName)”
}

Schedule this script via Azure Automation, Azure Functions (timer-triggered), or even GitHub Actions.

Add safeguards

Before deleting devices entirely, take these precautionary steps:

  • Dry-run mode – Log devices flagged for deletion without removing them.
  • Tagging – Add a custom attribute or tag devices as “stale_pending” to review first.
  • Approvals – Notify AAD admins with a summary report and wait for approval.

Bonus: Flagging stale devices with Conditional Access policy:

  • Target stale-device tag.
  • Require MFA or block sign-in.
  • Trigger an alert or conditional block when a stale device attempts access.

This layered approach maintains both proactive hygiene and reactive protection.

Zero Trust device lifecycle

By shifting device cleanup from a manual task to an automated, repeatable workflow, you’re scaling hygiene, cutting licensing waste, and reducing security risk. When paired with tagging, approvals, and policy enforcement, this becomes a robust companion to your overall Zero Trust posture on Azure.

NB

  • Adapt and test the script in your lab.
  • Schedule it via Azure Automation.
  • Pilot tagging/approval in a small group before rolling out globally.

This post contains AI-generated content, reviewed and curated by the admin and author.

 

 

 

Leave a Comment