What This Script Does
Keeping your Intune admin center clean and manageable is a critical task. Intune's device cleanup rules provide a straightforward way to hide inactive devices, ensuring you see only actively managed ones. This script helps automate the process, giving you a clear view of your device landscape. Use this when you need to efficiently manage device visibility without manual intervention.
Prerequisites: You must have PowerShell installed with at least version 5.1, the Microsoft Graph PowerShell module, and appropriate permissions to access Intune resources via the Graph API. Required scopes include "DeviceManagementManagedDevices.ReadWrite.All".
The Complete Script
<# .SYNOPSIS This script automatically hides inactive devices in Microsoft Intune .NOTES Author: Souhaiel MORHAG | msendpoint.com | GitHub: https://github.com/Msendpoint | License: MIT | Version: 1.0 #>[CmdletBinding()]param ( [int]$InactiveDays = 90 )try { Connect-MgGraph -Scopes "DeviceManagementManagedDevices.ReadWrite.All" $currentDate = Get-Date $thresholdDate = $currentDate.AddDays(-$InactiveDays) $devices = Get-MgDeviceManagementManagedDevice -Filter "enrollmentLastSyncDateTime lt $($thresholdDate.ToString('yyyy-MM-ddTHH:mm:ssZ'))" foreach ($device in $devices) { Write-Host "Hiding device: $($device.id), Last sync: $($device.enrollmentLastSyncDateTime)" Update-MgDeviceManagementManagedDevice -ManagedDeviceId $device.id -BodyParameter @{ state = 'retired' } } Write-Host "Device cleanup completed successfully."} catch { Write-Error "An error occurred: $_"}How It Works
This script uses Microsoft Graph API to interact with Intune-managed devices. It starts by connecting to the Graph API using the required scopes. The script calculates a threshold date based on user-input or default inactive days (90 days). It retrieves all devices that haven't synced since the threshold date and updates their state to 'retired', effectively hiding them from the admin center.
Usage & Parameters
To run the script with default settings:
powershell -File .\IntuneDeviceCleanup.ps1To specify a different number of inactive days:
powershell -File .\IntuneDeviceCleanup.ps1 -InactiveDays 60Sample output from running the script:
Connecting to Microsoft Graph...Hiding device: 12345, Last sync: 2026-01-01T12:00:00Device cleanup completed successfully.Customization Ideas
- To also include device model information, add "model" to the select statement in the Get-MgDeviceManagementManagedDevice cmdlet.
- For scheduled runs, configure a task in Windows Task Scheduler to execute the script at regular intervals.
- Modify the script to quarantine devices rather than hiding them by changing the state value to "quarantined".
- Integrate email notifications by adding a mail alert using Send-MailMessage to inform when the cleanup task is completed.
- Include detailed logging by outputting to a log file using Out-File for auditing purposes.