Deleting Inactive AD Computers from SCCM 2012

Share on:

I wrote the following script to find inactive computers in Active Directory and then find & delete them from SCCM. Feel free to use & abuse as you see fit, but always run through a test environment first. My version makes sure to target only Windows Operating Systems, and excludes anything with Server in the caption - you'll want to adjust the filter as needed in your specific environment.

 1# Import Necessary Modules 
 2
 3# Christopher Kibble, July 2014
 4
 5# Script will find inactive computers in AD (with defined filter) based on variable number of days since last logon timestamp
 6# and then will scour the CAS to remove those objects from AD.  Please note that the Resource IDs may not be cleared from all
 7# tables until a site maintenance task runs.
 8
 9# Credits:
10#  - Daniel Ratliff and "agressiv" (http://social.technet.microsoft.com/Forums/en-US/ff9a91f7-3df8-4e09-a0a5-9eff297ca0c9/powershell-equivalent-to-deleting-a-sccm-computer-object)
11#  - "TSO" (http://gallery.technet.microsoft.com/scriptcenter/Get-Inactive-Computer-in-54feafde)
12
13# Requires Configuration Manager Console (*Change as appropriate*)
14import-module "c:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
15
16# Requires Remote Server Administration Tools (RSAT)
17import-module activedirectory
18
19# 20 Weeks Offline considered inactive
20$DaysInactive = 140 
21
22# Date that is DaysInactive Ago
23$time = (Get-Date).Adddays(-($DaysInactive)) 
24  
25# Get all AD computers with lastLogonTimestamp less than our time that are Windows clients but not servers
26$oldComputers = Get-ADComputer -Filter {LastLogonTimeStamp -lt $time -and OperatingSystem -notlike "*Server*" -and OperatingSystem -like "*Windows*"} 
27
28$i = 0
29$iDeleted = 0
30$iSkipped = 0
31$max = $oldComputers.count
32
33# Loop Over Each Computer and Delete from SCCM
34$oldComputers | ForEach-Object { 
35	$i++
36	$pct = ($i/$max)*100
37	Write-Progress -Activity "Deleting Objects from SCCM - $_.Name" -Status "$i of $max" -percentcomplete $pct
38	# **** CHANGE THIS LINE BELOW TO MATCH YOUR SERVER NAME & SITE CODE **** 
39	$ResourceObject = Get-WmiObject -ComputerName "YOUR_SCCM_SERVER_NAME" -Namespace "ROOT\SMS\site_CAS" -Query "SELECT * FROM SMS_R_SYSTEM WHERE Name='$($_.Name)'"
40	If (!$ResourceObject) {
41		$iSkipped++
42	} else {
43		$ResourceObject.PSBase.Delete()
44		$iDeleted++
45	}
46}
47
48# Write Status
49write-host "$iDeleted Hosts Deleted and $iSkipped Hosts Skipped"


No comments