How Can I Delete an Active Directory Object that Contains Other Objects?
Hey, Scripting Guy! How can I delete an Active Directory object that contains other objects?
Hey, TS. Ah, yes, the dreaded “objects that contain other objects” dilemma. Is there a way to delete an Active Directory object that contains other objects? Let’s see if we can find one.
For those of you new to Active Directory scripting, deleting an object (a user account, a computer account, whatever) typically takes just two lines of code. For example, this little script deletes an object from Active Directory; it simply binds to the domain root (dc=fabrikam, dc=com) and then uses the Delete method to delete an OU (organizationalUnit) named Finance:
Set objDomain = GetObject("LDAP://dc=fabrikam,dc=com")
objDomain.Delete "organizationalUnit", "ou=Finance"
Well, check that: it deletes an OU named Finance provided that the OU is empty; that is, the OU will get deleted as long as it doesn’t contain any other objects. If Finance does contain other objects (for example, a bunch of user accounts) then the OU will not be deleted; instead, you’ll get this somewhat cryptic error message:
An invalid dn syntax has been specified.
Why is the syntax invalid? Well, the Finance OU is a container (an object that can contain other objects), and the Delete method cannot delete a container unless that container is empty. Because the Finance OU isn’t empty it’s not valid the call the Delete method. As a result, the syntax is invalid, and the script fails.
So what do we do about that? Well, we could get a list of all the objects stored in the Finance OU, delete each of those objects one-by-one, and then delete the Finance OU. Or we could use this script instead:
Set objOU = GetObject("LDAP://OU=finance,DC=fabrikam,DC=com")
Yes, it looks very similar, but there are a couple differences. To begin with, we bind directly to the Finance OU itself; in our previous script we bound to the parent object (in that case, the domain root). Second, we don’t use the Delete method; instead, we use the DeleteObject method. Unlike its counterpart, DeleteObject will delete an object regardless of whether or not it contains other objects. In one fell swoop, the Finance OU and everything in it will be deleted.
Note, too that we passed DeleteObject a single parameter: 0. This is a required parameter; leave it out and the call to DeleteObject will fail. Interestingly enough, however, 0 is the only possible value that can be passed to DeleteObject; there are no options other than 0, which means, “Go ahead and delete everything.” Why? To tell you the truth we don’t know, just like we don’t know for sure why there are two methods (Delete and DeleteObject) for deleting things from Active Directory. But you know what they say: when it comes to certain things – like what they put into hot dogs and how they delete objects from Active Directory – well, maybe you’re better off not knowing. Just use DeleteObject and delete away.