Intune devices on-premises AD cleanup
What is it?
So when we Hybrid Azure AD join devices, we have the computer enrolled into Intune, AAD registered (through the Hybrid join), and joined on-premises in the Active Directory. The most modern attempt to manage your devices is only using the endpoint manager portal. At the end of the lifecycle, when it comes to decomissioning a client, I do prefer to delete the device in Intune. To mention everything; there are more options like wipe and retire or Autopilot reset and fresh start, to revive the device.
But what about the on-prem records? Unfortunately does not delete the computer at the time. This means the dead computer body object will persist, maybe even leave a security concern. So I thought I need to get an automated solution for this case. Then I decided to write following script:
This script will query your Intune tenant, as well as your local Active Directory, where Intune devices are stored. Please make sure, that you only have Intune device objects in the OU, that you provide. Subsequently all records of computers that are only existing in AD, but not in Intune, will be listed and can be deleted. This will clean up your AD from legacy or decomissioned computers. Please make sure that you run this script with access to Active Directory and use an account for Microsoft online authentication, that is permitted to use Intune Graph to get device information.
Run the script at your own responsibility. It is meant to do the best, but without any warranty. (Make sure you have a backup or the AD recycle bin enabled for emergency.)
You can find the script on my GitHub repo.