Automatically remove inactive devices that do not exist in AD

The following script will query Configmgr for inactive devices and automatically remove them if they are no longer in Active Directory. Personally I prefer this simple script over the built in Configmgr maintenance task (Delete Inactive Client Discovery Data) because the task does not check Active Directory and it will remove any inactive device with the criteria that you have configured. By default, this maintenance task will remove any device that has been inactive for 90 days. At least in my environment, if a computer does not exist in Active Directory it should not be in MEMCM so I have the script run on a daily basis as a scheduled task to remove the devices that are not in AD.

Keep in mind to not run this script if you have workgroup computers because they will be deleted since they are not in AD.

Powershell Scripts:

Single Domain Environment:

$InactiveClients = Get-CMDevice | Where-Object { $_.ClientActiveStatus -eq 0 -or $_.ClientActiveStatus -eq $null -and $_.Name -notlike "*Unknown Computer*"}

ForEach($InactiveClient in $InactiveClients) {
    
    Try {

        If(-not(Get-ADComputer -Identity $($InactiveClient.Name))) { }

    }
    Catch {
    
        Write-Host "Removing: $($InactiveClient.Name)"
        Remove-CMDevice -Name $($InactiveClient.Name) -Force
    
    }

}

Multi Domain Environment:

$InactiveClients = Get-CMDevice | Where-Object { $_.ClientActiveStatus -eq 0 -or $_.ClientActiveStatus -eq $null -and $_.Name -notlike "*Unknown Computer*"}

$Domains = (Get-ADForest).Domains

[System.Collections.ArrayList]$Computers = @()


ForEach($InactiveClient in $InactiveClients) {

    ForEach($Domain in $Domains) {

        Try {

             If(-not(Get-ADComputer -Identity $($InactiveClient.Name) -Server $Domain)) { }

 
        }
        Catch {
     
            $Computers += $InactiveClient.Name
     
        }
        

    }
 
}

$ComputersNotInAD = ($Computers | Group-Object | Where-Object { $_.Count -eq $Domains.Count }).Values

Foreach($Computer in $ComputersNotInAD) {

    Write-Host "Removing: $Computer"
    Remove-CMDevice -Name $Computer -Force

}

4 Comments

  1. how we can run this , i tried running this but it is bypassing AD check and directly start removing one by one , mean it is getting Inactive client list but not comparing with AD and start removing

    if you please let me know if any pre req to run this or what are steps to run this

  2. Running this manually works but running it through Task Scheduler doesn’t. It just sits there, i inserted a start-transcript in the script to see if the task did run.

    • Jose Espitia

      May 15, 2023 at 8:10 pm

      Could be a permission issue with the service account that you are using to run the task scheduler.

Leave a Reply