Skip to content
Branch: master
Find file Copy path
Find file Copy path
1 contributor

Users who have contributed to this file

62 lines (53 sloc) 2.37 KB
This script cleans up duplicated device entries in the intune environment based on the serial number.
The script retrieves all devices from Intune and elaborates all old devices per serial number. Only the newest device (Last Synced) will stay in the environment.
Retrieve devices to remove and displays them first in a Out-Gridview, to select the one which should be removed.
Invoke-IntuneCleanup -Whatif | Out-GridView -OutputMode Multiple | foreach-Object { Remove-DeviceManagement_ManagedDevices -managedDeviceId $ }
This command automatically removes duplicated objects based on the serial number.
Version: 1.0.0
Author: Thomas Kurth
Creation Date: 14.9.2019
Purpose/Change: Initial script development
Begin {
Write-Verbose "Check Intune Connection"
$GraphConnection = Get-MSGraphEnvironment
if($null -eq $GraphConnection){
throw "Not connected to MS Graph please invoke 'Connect-MSGraph' before invoking this Cmdlet."
Process {
$devices = Get-IntuneManagedDevice
Write-Verbose "Found $($devices.Count) devices."
$deviceGroups = $devices | Where-Object { -not [String]::IsNullOrWhiteSpace($_.serialNumber) } | Group-Object -Property serialNumber
$duplicatedDevices = $deviceGroups | Where-Object {$_.Count -gt 1 }
Write-Verbose "Found $($duplicatedDevices.Count) serialNumbers with duplicated entries"
foreach($duplicatedDevice in $duplicatedDevices){
# Find device which is the newest.
$newestDevice = $duplicatedDevice.Group | Sort-Object -Property lastSyncDateTime -Descending | Select-Object -First 1
Write-Verbose "Group $($duplicatedDevice.Name)"
Write-Verbose "# Keep $($newestDevice.deviceName) $($newestDevice.lastSyncDateTime)"
foreach($oldDevice in ($duplicatedDevice.Group | Sort-Object -Property lastSyncDateTime -Descending | Select-Object -Skip 1)){
Write-Verbose "# Remove $($oldDevice.deviceName) $($oldDevice.lastSyncDateTime)"
} else {
Remove-DeviceManagement_ManagedDevices -managedDeviceId $
End {
You can’t perform that action at this time.