Clean SCCM DB from unwanted discovered computers

From time to time I encounter a system where SCCM discovered some unwanted computers and Client Push installation cannot be activated because it will install the SCCM client on exactly those computers. So I have written a script to remove those computers from SCCM DB.

Basically, I have identified that the unwanted computers were discovered by the ‘Active Directory Group Discover’ agent. This agent is called ‘SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT’ by the SCCM. I have identified this by going to the unwanted computer on the SCCM console and viewing it properties:

Unwanted computer agent

Unwanted computer agent

In the above example the agent name is ‘SMS_AD_SYSTEM_DISCOVERY”, but you get the idea.

The following script gets all the computers in SCCM and removes every computer where the agent discovery name is ‘SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT’. You can change the agent name in the beginning of the script. Each computer that is removed is written to a log file located in the %TEMP% folder.

As you can see in the script, I use PowerShell to query WMI for the SiteCode and the computers list. Also, please note the location of the Configuration Manager PowerShell module. In my case it was installed in the default installation folder. If you have moved it to a different folder, please change the script.

If you have any questions about the script feel free to post them in the comments section.

[PowerShell]

# Name of agent that discovered the devices to remove
$AgentName = ‘SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT’

# Change to the Installation Directory of Configuration Manager
$CMModulePath = ‘C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin’
$CMModule = $CMModulePath + ‘\ConfigurationManager.psd1’

# Now Import that module
Import-Module $CMModule

# Set location for log file
$LogPath = $env:TMP + “\SCCM_Remove_OLD_Devices” + (Get-Date).ToString(“d_M_h_m_s”) + “.log”

# Get CM Site Code
$SiteCode = (Get-WMIObject -ComputerName “$ENV:COMPUTERNAME” -Namespace “root\SMS” -Class “SMS_ProviderLocation”).SiteCode

# Set drive location
$PSDriveLocation = $SiteCode + “:”
Set-Location $PSDriveLocation

# WMI NameSpace to query
$NameSpace = ‘root\sms\site_’ + $SiteCode

# Get all computers in SCCM
$AllCMDevices = Get-WmiObject -Query “select * from sms_r_system” -Namespace $NameSpace

# Remove devices
ForEach($CMDevice in $AllCMDevices)
{
if(($CMDevice.AgentName).Count -eq 1 -and $CMDevice.AgentName -eq $AgentName)
{
Try
{
Remove-CMDevice -DeviceId $CMDevice.ResourceId -Force
$Value = “Success! Removed device:” + $CMDevice.Name
}
Catch
{
Write-Host “cannot remove” $CMDevice.ResourceId
$Value = “Failure! Could not remove device: ” + $CMDevice.Name
}
add-content -Path $LogPath -Value $Value
}
}

[/PowerShell]

What do you think about this post?