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.
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.
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.
Reports
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
Download get-AzureADInactiveDevices.ps1 from Gitlab
Disclaimer
As always, the script is provided as-is and should be reviewed and then used at your own risk.