Wednesday, March 20, 2013

PowerShell: Remove Computer Object from Active Directory (or modify object properties)


This technique bypasses the need to load the Active Directory module and has been tested in PowerShell 2.0 & 3.0.  The CN= reference can be either a computer or user.  This script connects to your domain and searches for an object you assign via the variable $oldcomp.  You can also change the objects properties once found in AD.  That's described in the second part of the script.

#Grab your local domain for ADSI

$searcher = [adsisearcher][adsi]""

#Create $oldcomp however you like then use it as input for the ADSI searcher

$searcher.filter ="(cn=$oldcomp)"

#Search Active Directory for the current location of the computer object

$searchparm = $searcher.FindOne()

#Assign $deleteoldcomp to the found path

$deleteoldcomp = $searchparm.path

#Assign the ADSI object to a variable

$delcomp = [adsi]("$deleteoldcomp")

#I used the Try/Catch sequence in case the computer wasn't found in AD.
#the deletetree() removes the object from the domain, not the computer 
#itself.  Stop here if you only want to find the object and then edit its 
#properties.  If you wish to delete it, then add this next line:

try {$delcomp.deletetree()}catch{}

After you have found the computer object, you are able to edit its properties.  If you take the $delcomp object and type $delcomp|format-list * then you'll see information about your object.  To change your computer object properties:

#To change the computer description property

$delcomp.description = [string]"Whatever String Value you want"

#To assign a technician in the ManagedBy property, copy/paste the 
#technicians user object

$delcomp.managedby = "CN=TechnicianUserID,OU=..."

Use the same technique to assign other property values.  When you are finished, you'll need to save your changes back to the computer object.  Ensure your account has the correct credentials.

$delcomp.setinfo()