Over time, devices connected to Microsoft Entra ID (formerly known as Azure AD) can become stale, inactive, or duplicated. Having a list of inactive or stale devices for cleanup helps IT administrators take informed actions, optimize licensing, and maintain a clean Azure environment.
This guide teaches users how to use PowerShell and Microsoft Graph API to identify, export, and automate Azure AD cleanup of joined stale devices.
Exporting the CSV file of stale Azure AD-joined devices: a step-by-step guide
To remove inactive devices on Azure AD, you’ll need a list of inactive devices first. This section guides users through a step-by-step process of exporting the CSV file via PowerShell.
📌 Prerequisites:
The following are required for the core process of exporting the CSV file:
- Azure AD or Entra ID admin permissions
- Microsoft Graph API access with the following permissions:
- Device.Read.All
- Directory.Read.All
- PowerShell 7+
- Microsoft.Graph module installed
Additionally, users may also want to have an RMM agent and registry access for additional steps after exporting a CSV.
Step 1: Connect to Microsoft Graph and retrieve the device list
Follow these steps:
- Connect to Microsoft Graph and authenticate the connection using the command:
Connect-MgGraph -Scopes “Device.Read.All Directory.Read.All”
- Retrieve the device list with the command: $devices = Get-MgDevice -All
Step 2: Filter stale or inactive Azure devices
Identify stale or inactive Azure devices based on when they were last active. To do this, define the cutoff for inactivity with the command:
$cutoff = (Get-Date).AddDays(-90)
$inactiveDevices = $devices | Where-Object {
$_.ApproximateLastSignInDateTime -lt $cutoff
}
💡 TIP: To have a more accurate list, you can also exclude service accounts and hybrid objects using this command:
$inactiveDevices = $inactiveDevices | Where-Object {
# Exclude Hybrid Azure AD Joined devices
$_.DeviceTrustType -ne “HybridAzureADJoined” -and
# Exclude Personally Owned devices (keep only Corporate owned)
$_.DeviceOwnership -eq “Company”
}
Alternative method: How to find inactive users in Azure Active Directory
You can also find inactive users in the Entra admin center. To do this, go to Monitoring > Sign-ins, then filter by users who haven’t logged in within a defined time window (e.g., 30, 60, 90 days).
Step 3: Export the CSV file
To export the CSV file, use this command:
$inactiveDevices | Select-Object DisplayName, Id, DeviceId,
DeviceTrustType, ApproximateLastSignInDateTime |
Export-Csv -Path “C:\Reports\InactiveAzureDevices.csv” -NoTypeInformation
Once exported, the CSV can be used for documentation, approval workflows, and import to cleanup scripts.
How to tag devices for local cleanup & how to remove stale computers from Active Directory
Aside from the three main steps listed above, users can continue to the cleanup process with the following methods:
Tag devices for local cleanup on Windows Registry via PowerShell
Tagging devices is helpful when you have device access via RMM or scripts. When tagged, RMM and script tools can identify which devices are considered stale, allowing the tools to coordinate cleanup actions safely.
Execute this command on PowerShell:
New-Item -Path “HKLM:\SOFTWARE\Org\DeviceCleanup” -Force
Set-ItemProperty -Path “HKLM:\SOFTWARE\Org\DeviceCleanup” -Name “CleanupStatus” -Value “MarkedInactive”
Set-ItemProperty -Path “HKLM:\SOFTWARE\Org\DeviceCleanup” -Name “MarkedDate” -Value (Get-Date).ToString(“u”)
Run the following line in Command Prompt to verify if changes have been applied:
reg query HKLM\SOFTWARE\Org\DeviceCleanup
Remove stale devices on Azure AD
There are two ways to clean up stale, inactive, or duplicate devices on Azure AD: via Microsoft Graph removal or via Azure Portal.
Cleanup device via Microsoft Graph
To remove a device directly via Graph:
Remove-MgDevice -DeviceId $device.Id
⚠️ Important: Deploying this command makes immediate and permanent removals. It does not move devices to a recycle bin. Proceed with caution.
Cleanup AD-joined stale device via Azure Portal
Azure Portal has a bulk delete feature that allows users to clean up multiple inactive devices. Go to Azure Portal > Entra ID > Devices > Bulk Actions > Delete.
Additional considerations when cleaning up or marking AD-joined devices as inactive
Multi-factor authentication and conditional access policies
When a device is tied to a user’s access, ensure that you review whether it is part of MFA or conditional access flows. Deleting a device that is still tied to a user’s access requirements may bar the user from accessing company apps, VPNs, and other important files.
Licensing
Intune, Microsoft Defender, Microsoft tools, and other tools will often have a license per registered device. Inactive and duplicate devices usually still consume these licenses. If you notice that you have a lot of stale devices in your organization, consider cleaning up to free up licenses for organizational use.
Hybrid environments
In a hybrid environment, devices can join either through on-prem AD or the Entra directory. Deleting a hybrid device without confirming its join type can cause issues, such as inconsistent join states. Always consider the hybrid join status before deletion.
Auditing and documentation
Clean-up actions are usually part of routine IT management processes related to compliance, security audits, and licensing management. Having a log of removed devices and their status helps maintain consistency in your documentation and ensures no unauthorized deletions were made.
Troubleshooting common issues
CSV is not exported
This issue occurs when the CSV export (Step 3) fails. It occurs because the path doesn’t exist, the user doesn’t have the appropriate permissions, or the user used a relative path in a session that doesn’t resolve correctly. To resolve this, validate the output path or use the full path in $env: TEMP.
Permission denied
Users who don’t include the necessary scopes when connecting to Microsoft Graph can be blocked from retrieving device data. To prevent or resolve permission denial, ensure that you have the appropriate admin role and permissions and include the appropriate Graph API scopes.
Empty ApproximateLastSignInDateTime
An empty ApproximateLastSignInDateTime indicates that a device has never been signed in or that telemetry is not available. When this occurs, cross-check the device data with other tools such as Intune, RMM, or the last AD sync before marking it inactive.
Graph throttling
Microsoft Graph limits the number of requests you can make within a given timeframe, especially in larger environments. Add delays or paging if operating on large environments.
NinjaOne services that help with device cleanup workflows
As a tool, NinjaOne supports inactive device cleanup through the following services:
- Deployment of cleanup scripts or registry markers across devices
- Registry values (e.g., CleanupStatus) reporting for endpoint-level tracking
- Automated alerting on endpoints marked inactive or not checked in within a threshold
- Device tagging based on role, site, or status for follow-up action
- Providing visibility across tenants into the cleanup history and device churn
These services help bridge the gap between cloud identity cleanup and endpoint operations.
Maintain identity and licensing organization with regular AAD device audits and removal
Regular auditing of Azure AD device inventory is essential for clean identity governance and efficient licensing. This guide covered how to use PowerShell to export your starting CSV file and the next steps for efficient inactive device removal.
Related topics:
