Friday, December 30, 2011

VBScript–Unable to delete computer account

I discovered this morning that a vbscript use to delete inactive computer accounts is not working.  Below is the script snippet that does the deletion.

Set objContainer = GetObject("LDAP://OU=InactiveComps,OU=Clients,DC=deInfoTech,DC=Org)

Do Until objRecordSet.EOF
    strComputerDN = objRecordSet.Fields("distinguishedName") 
    Set objComputer = GetObject("LDAP://" & strComputerDN)
    objContainer.Delete "computer", "cn=" & objComputer.cn 
    objRecordSet.MoveNext
Loop

Below is the error message that I received when trying to run the script.

D:\CompAcctDelete\DeleteInactiveComp.vbs(80, 4) (null): The directory service can perform the requested operation only on a leaf object.

This means that the computer account contains other objects thus not a leaf object.  I am able to those hidden objects by viewing computers as containers in ADUC (Active Directory Users and Computers) MMC.

image

image

In the above example, the computer account contains a printer object.  If I delete the printer object and run the script again, the computer account will be deleted successfully.

However, that defeats the purpose of having a script to automate the clean up.  So the solution is to use DeleteObject method.  Replace the line objContainer.Delete "computer", "cn=" & objComputer.cn with objComputer.DeleteObject(0).

Below is the modified script snippet.

Set objContainer = GetObject("LDAP://OU=InactiveComps,OU=Clients,DC=deInfoTech,DC=Org)

Do Until objRecordSet.EOF
    strComputerDN = objRecordSet.Fields("distinguishedName") 
    Set objComputer = GetObject("LDAP://" & strComputerDN) 
    objComputer.DeleteObject(0)
    objRecordSet.MoveNext
Loop

The DeleteObject method will delete an object and all its child objects.

1 comment:

Prince Arora said...



The blogs are really appreciable and one can trust the knowledge and information provided in the writing.
The article you do produce on a weekly base really the best. I have found a similar website Please Check This One.signs makers,awning signs visit the site to know more about sinking