Here’s another script to delete obsolete records from SCCM. I know there’s a task for this and various other ways but sometimes a script is handy.
Check the script first to make sure any wrapping caused by posting it here hasn’t messed things up.
'=====================================
'DeleteObsoleteRecords - Deletes all obsolete records
'Author: Stuart James
'
'Requirements: Run on the site server with account that has necessary rights
'
'Usage: CScript DeleteObsoleteRecords.vbs or double click
'=====================================
'Check we're using CScript and if not then relaunch
If "CSCRIPT.EXE" <> UCase(Right(WScript.Fullname, 11)) Then
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "CSCRIPT.EXE /nologo " & WScript.ScriptFullName
Wscript.Quit
End If
' Setup a connection to the local provider.
Set swbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set swbemServices= swbemLocator.ConnectServer(".", "root\sms")
Set providerLoc = swbemServices.InstancesOf("SMS_ProviderLocation")
For Each Location In providerLoc
If location.ProviderForLocalSite = True Then
Set swbemServices = swbemLocator.ConnectServer(Location.Machine, "root\sms\site_" + Location.SiteCode)
Exit For
End If
Next
'Main call
QueryObsoleteClients swbemServices
Sub QueryObsoleteClients(connection)
'Queries for obsolete clients and for any it finds calls DeleteResource
On Error Resume next
Dim resources
Dim resource
' Run the query.
Set resources = connection.ExecQuery("Select * From SMS_R_System where Obsolete = '1'")
If Err.Number<>0 Then
Wscript.Echo "Couldn't get resources"
Wscript.Quit
End If
For Each resource In resources
Wscript.echo "Found obsolete resource: " & resource.Name & ", " & resource.ResourceID
DeleteResource connection,resource.ResourceID
Next
If resources.Count=0 Then
Wscript.Echo "No resources found"
End If
End Sub
Sub DeleteResource (connection, resourceID)
'Deletes a specific resource
On Error Resume Next
Dim resource
Wscript.echo "Attempting to delete resource with ID " & ResourceID
Set resource = connection.Get("SMS_R_System.ResourceID='" & resourceID & "'")
If Err.Number<>0 Then
Wscript.Echo "Couldn't get resource " + resourceID
Exit Sub
End If
resource.Delete_
WScript.Echo "Resource deleted"
If Err.Number<>0 Then
Wscript.Echo "Couldn't delete " + resourceID
Exit Sub
End If
End Sub
'Add pause to end in case script was double clicked so we can review what happened
WScript.Echo "=== F I N I S H E D ==="
strMessage = "Press the ENTER key to continue. "
Wscript.StdOut.Write strMessage
Do While Not WScript.StdIn.AtEndOfLine
Input = WScript.StdIn.Read(1)
Loop