Remove old Active Directory computer accounts from SCCM

A common issue in IT organizations is that the removal of computer objects is not done regularly. While I’ve presented scripts for removing old computer accounts from Active Directory, I’ve recently had to extend the removal of legacy computers into other systems such as SCCM.

Because SCCM dynamically discovers computers, but does not remove them I’ve created this short script which scans the Active Directory for computer accounts which have been off the network for more than a certain number of days (45 is my preferred number).

The next thing that you will need to do is to make sure that you move those computer accounts to an OU which is not discoverable by SCCM, or delete them from Active Directory altogether so that they are not re-discovered. This script simply removes them from SCCM.

The code at the end of the article is also stored at my TechNet Gallery page here or you can go directly to the article from this link:

http://gallery.technet.microsoft.com/Remove-old-Active-7fc40c61

In order to really keep a clean Active Directory, you should also make use of other processes such as my Organize Computers by Subnet IP which you will find here:

http://gallery.technet.microsoft.com/PowerShell-Organize-d37c2a29

The full article on that process is here.

Here’s the code:

# Environment setup 
# Import the ActiveDirectory module to enable the Get-ADComputer CmdLet 
Import-Module ActiveDirectory 

$SCCMServer = “YOUR SCCM SERVER” 
$sitename = “YOUR SCCM SITE” 
$old = (Get-Date).AddDays(-45) # The threshold for what we consider to be old (current set as 45 days) 

# Find the computers in Active Directory which are “old” 
$oldComputers = Get-ADComputer -Filter {PasswordLastSet -le $old} -Properties * 

ForEach ($oldComputer in $oldComputers) { 
    # Select the computer(s) 
    $computername = $oldComputer.name  

    # Get the resourceID from SCCM 
    $resID = Get-WmiObject -computername $SCCMServer -query “select resourceID from sms_r_system     where name like `’$computername`'” -Namespace “rootsmssite_$sitename” 
    $computerID = $resID.ResourceID 

    if ($resID.ResourceId -eq $null) { 
        $msgboxValue = “No SCCM record for that computer” 
        } 
    else 
        { 
            $comp = [wmi]”\$SCCMServerrootsmssite_$($sitename):sms_r_system.resourceID=$($resID.ResourceId)”  

            # Output to screen 
        Write-Host “$computername with resourceID $computerID will be deleted” 

        # Delete the computer account 
            $comp.psbase.delete() 
    } 
}

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.