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, here’s 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.
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. If doing cleanup, also add the managed identity to the cloud device administrator (Azure AD) role.
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.
Disable vs Delete
The runbook also has a disable option, in which it will first disable a device and wait a configurable ($disableDurationInDays) period of time before actually deleting a device.
If you wish, you can also let the script mail you a report in CSV format. Add the Mail.Send graph permissions like you did with device permissions and give the MailFrom and MailTo parameters a value.
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.
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 »
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:
I am not able to run this script on local. please advise.