Microsoft Intune: Device Cleanup rules

Published on: August 10, 2021 | Reading Time: 2 min | Last Modified : August 10, 2021

Intune Device clean-up rules and Azure AD (Opt)

Today, Let’s know how we can configure Device Clean-up rules in the MEM Console. Now, if you are little familiar with this console, you might have noticed that there are several test/stale devices ie unwanted devices present in the console. To overcome this, we will need a solution to keep the console always clean. Intune has facilitated a Out-of-Box solution known as Intune clean-up rules in intune console.

Steps

  1. Sign in to the Microsoft Endpoint Manager admin center
  2. Choose Devices > Device cleanup rules > Yes.
  3. In the Delete devices that haven’t checked in for this many days box, enter a number between 30 and 270. SyncfromIntune3.png
  4. [Optional] Select View affected devices.
  5. [Optional] Select Export and double check if it’s populating correct data SyncfromIntune3.png
  6. Choose Save.

Limitations

In addition to some limitations stated by Microsoft, this cleanup rules deletes the devices from Intune only and not from Azure AD reason being if same device sync again frequently it should re-enroll device automatically (Ex- If Employee goes for long leave, their device need not be reimaged/undergo Autopilot). Now suppose, if you want to clear test devices parmanently from Intune an from Azure ?? Here comes our new topic..

PowerShell to delete stale device from Azure AD

I have created a script to meet that scenerio. Let’s have a look-

#Requires -Modules AzureAD 
#Install-Module AzureAD if required
#Enter threshold days 
$deletionThresholdDays= 90
Connect-AzureAD 
$deletionThreshold= (Get-Date).AddDays(-$deletionThresholdDays)
$AndroidDevices=Get-AzureADDevice -All 1 -Filter
"startswith(DeviceOSType,'AndroidForWork')" 
$iosDevices=Get-AzureADDevice -All 1 -Filter "startswith(DeviceOSType,'IPhone')"
$allDevices=$AndroidDevices+$iosDevices | Where {$_.ApproximateLastLogonTimeStamp -le $deletionThreshold}
$PSScriptRoot='c:\logs'
$ExportPath=$(Join-Path $PSScriptRoot "AzureADDeviceExport.csv")
$AllDevices | Select-Object -Property DisplayName, ObjectId, ApproximateLastLogonTimeStamp, DeviceOSType, DeviceOSVersion, IsCompliant, IsManaged `
| Export-Csv -Path $exportPath -UseCulture -NoTypeInformation
Write-Output "Find report with all devices under: $exportPath"
$ConfirmDeletion=$null
while ($ConfirmDeletion -notmatch "[y|n]"){
    $ConfirmDeletion = Read-Host "Delete all Azure AD devices which haven't contacted your tenant since $deletionTresholdDays days (Y/N)"
}
if ($ConfirmDeletion -eq "y"){
    $AllDevices | ForEach-Object {
        Write-Output "Removing device $($PSItem.ObjectId)"
        Remove-AzureADDevice  -ObjectId $PSItem.ObjectId
    }
} else {
    Write-Output "Exiting..."
}

Here, I’m going to put the helpful links which will help you understand some insights-

References