How to Clean Up Stale Devices in Microsoft Entra ID Using PowerShell

Listen to this Post

Featured Image
Stale devices in Microsoft Entra ID (formerly Azure AD) can clutter your tenant, making device management inefficient. A stale device is one that hasn’t accessed any cloud applications for a specified period. These devices can impact security, compliance, and administrative overhead.

Steps to Identify Stale Devices

1. Access Microsoft Entra Portal:

  • Navigate to entra.microsoft.com → Identity → Devices → Overview.
  • Review inactive devices.

2. Use PowerShell for Bulk Cleanup:

  • Microsoft Graph API with PowerShell can automate stale device removal.

PowerShell Script for Stale Device Cleanup

Requirements:

  • An Enterprise Application with Device.ReadWrite.All permissions.
  • PowerShell Microsoft.Graph module.

Install Required Module

Install-Module Microsoft.Graph -Force 

Connect to Microsoft Graph

Connect-MgGraph -Scopes "Device.ReadWrite.All" -TenantId "your-tenant-id" 

List Stale Devices (Inactive for 180 Days)

$daysInactive = 180 
$inactiveDate = (Get-Date).AddDays(-$daysInactive)

$staleDevices = Get-MgDevice -All | Where-Object { 
$_.ApproximateLastSignInDateTime -lt $inactiveDate 
}

$staleDevices | Select-Object DisplayName, DeviceId, ApproximateLastSignInDateTime 

Delete Stale Devices (Uncomment to Execute)

foreach ($device in $staleDevices) { 
Remove-MgDevice -DeviceId $device.Id 
Write-Host "Deleted: $($device.DisplayName)" 
} 

🔹 Important: Test first! Uncomment deletion only after verifying the list.

You Should Know:

  • Device Writeback Impact: If hybrid Azure AD join is enabled, stale devices may sync back from on-prem AD.
  • Security Risks: Old devices may have outdated policies, increasing vulnerability.
  • Audit Logs: Check Azure AD Audit Logs post-cleanup for verification.

Additional Useful Commands

  • Check Device Compliance (Intune):
    Get-MgDeviceManagementManagedDevice -Filter "complianceState eq 'noncompliant'" 
    
  • Export Stale Devices to CSV:
    $staleDevices | Export-Csv -Path "StaleDevices.csv" -NoTypeInformation 
    

What Undercode Say

Managing stale devices is crucial for maintaining a secure and efficient Microsoft Entra environment. Automating cleanup with PowerShell ensures better tenant hygiene and reduces attack surfaces.

Expected Output:

Deleted: Laptop-DEV-001 
Deleted: TestVM-OLD 
Deleted: UserTablet-2020 

For further reference:

References:

Reported By: Danieljeanschmidt Did – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram