Under normal circumstances, when powering off Azure Active Directory (AAD) joined non-persistent VM, MCS agent inside VM will perform Azure AD leave and remove device record from Azure Active Directory. Occasionally, the action may fail, it will leave stale device in Azure AD. Recently, Azure AD started blocking Azure AD join when a device with same hostname is already registered. There is a known issue recorded, refer to Known issues | Citrix DaaS
Before Citrix officially resolve this issue in product, customer admin can use the Microsoft Graph API to filter out the eligible device records of the Azure AD devices based on the NamingScheme of the non-persistent Azure AD joined Machine Catalog, and then delete device records of those VMs that no longer exist in Azure AD. Then new VM with same host name can join Azure AD. We recommend the operation to be run as a scheduled task to ensure the stale device records can be removed in time.
You can use the script CleanDeviceByAzureFunction.ps1 in the Azure Function (run as a regular task to clean the stale device, set to run every N minute to make sure the stale device can be removed timely):
Create an Azure function, and “Runtime stack” is “Powershell Core”.
Should uncomment the line below “# 'Az' = '9.*'” in “requirements.psd1” file under “App files” of Azure function, to use the Az module in your function app.
Enable “System assigned” managed identity or “User assigned” managed identity.
Assign at least “Reader” role assignment to the managed identity, and scope should be subscription/resource groups of those deleted VMs whose Azure AD devices are requested to be cleaned up.
Assign the managed identity with Azure AD role of “Cloud Device Administrator” and API permission of "DeviceManagementManagedDevices.ReadWrite.All".
Download the CleanDeviceByAzureFunction.ps1 and copy code into Azure function.
Note: depending on the template used to create a function, some changes are required:
If use User assigned managed identity, modify file “profile.ps1” under “App files” of Azure function.
Connect-AzAccount -Identity -AccountId "The Client ID of managed identity"
Set “$CleanIntuneDevice” to be $True if want to clean Azure AD device's record in Intune.
Set "$NamingScheme", and the naming scheme should be between 2 and 15 characters
If non-persistent catalog has preserving VM option enabled, then the script will not work correctly. Admin needs to remove stale Azure AD device manually or by a script that is based on power schedule of VM, in other words, delete Azure AD stale device after VM is shutdown.