Automated Stale Device Cleanup in Azure Active Directory using a runbook

As with cleaning up inactive guest users, inactive devices also pose several issues for organizations.

Microsoft recommends cleaning up stale devices after 90 days, but does not provide a service option or automation to do so.

Therefore, another runbook you may run to just report on your inactive devices, or to automatically (and optionally periodically) clean up inactive devices in your environment when the removeInactiveDevices switch is supplied.

Managed identity

When run locally, interactive sign in is required. When running as a runbook in Azure automation, the Managed Identity of the automation account is leveraged. This requires you to set Device.ReadWrite.All or Device.Read.All permissions depending on if you want to script to do the cleanup as well.

Autopilot / on premises devices

Note that the script will log an error (and not attempt to delete the device) when a device is an autopilot record (not a real device) or when the device is synced from an on-premises active directory.


Download get-AzureADInactiveDevices.ps1 from Gitlab


As always, the script is provided as-is and should be reviewed and then used at your own risk.

Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Christian Schroeder
Christian Schroeder
8 days ago

Hi Jos,

thank you for your script and how-to. I assigned the device.readwrite.all permission to the managed identity but got every time a 403 access denied error code back during the device deletion. I added the managed identity to the cloud device administrator role and it worked as expected. Do you have a hint for me?

I found only this comment via google:

29 days ago

Thanks for this post. I’m working on the same problem at the moment and it was really helpful to see that you have mostly tackled the problem in the same way. I do like your clean code and think I will take a few tips from that for sure! A few different decisions I’ve taken: I use the Graph PowerShell SDK which makes authentication and Graph calls a little easier, in my opinion. I write to an Azure Table for reporting in PowerBI instead of the csv output. I’m currently working on performing a wipe and retire on Intune-managed devices… Read more »