How Can I Prompt a User to Delete (or Not Delete) a Computer Account?

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I delete a computer account from Active Directory, but provide a Yes/No prompt to the user before the account is actually deleted?

— NM

SpacerHey, Scripting Guy! AnswerScript Center

Hey, NM. Let’s start by showing you how to delete a computer account from Active Directory. But don’t worry; that won’t take long. In fact, it only takes two lines of code:

Set objComputer = GetObject _
(“LDAP://CN=atl-ws-01, CN=Computers, DC=fabrikam, DC=com”)
objComputer.DeleteObject (0)

As you can see, we bind directly to the account we want to delete (this one happens to be a workstation named atl-ws-01, which can be found in the Computers container in After that we call the DeleteObject method, which immediately deletes the account from Active Directory. (Incidentally, the (0) parameter is required, even though the only allowed value is 0. Leave it out and the script will fail.)

As we noted, the moment you call the DeleteObject method that object is deleted from Active Directory. So how can we prompt the user with an “Are you sure you want to delete this account?” prompt? Well, what we need to do is bind to the account, issue the prompt, and only then delete the account (assuming, of course, that the user answers Yes). Here’s a sample script that does just that:

Set objComputer = GetObject _
(“LDAP://CN=atl-ws-01, CN=Computers, DC=fabrikam, DC=com”)
strComputer = objComputer.CN

intReturn = Msgbox(“Are you sure you want to delete this computer account?”, _
vbYesNo, “Delete ” & strComputer)

If intReturn = vbYes Then
objComputer.DeleteObject (0)
End If

Here’s how the script works. We bind to the computer account, and then retrieve the CN (Common Name) for that account. Note that we don’t really have to grab the CN; we just do that so we can include the computer name in our prompt. We then use VBScript’s Msgbox method to display a message box that includes: 1) a Yes button and a No button (that’s what the vbYesNo constant does for us); 2) displays the message Are you sure you want to delete this computer account?; and, 3) just for the heck of it, sets the title of the message box to Delete atl-ws-01 (the word Delete followed by the CN of the computer).

The message box will stay on screen until the user clicks one of the two buttons (Yes or No); as soon as a button is clicked, a value corresponding to that button is assigned to the variable intReturn. We then check the value of intReturn. If intReturn is equal to the VBScript constant vbYes, then the Yes button was clicked; in that case, we go ahead and delete the computer account. If intReturn is equal to anything else (the only other possibility would be vbNo, meaning the No button was clicked) we don’t do anything at all, the script ends, and the account is not deleted.