Guy’s Scripting Ezine 134 – Delete Users and Other AD Objects

Delete Users and Other Active Directory Objects

These scripts have the potential to delete users in your Active Directory domain. Because deleting the wrong users could be devastating, before the script actually deletes any user accounts, I have deliberately left some editing for you to do.

 ♣

This Week’s Secret

Last month a visitor to my site modified one of my registry scripts and unfortunately crippled his machine.  I felt bad.  Did it help to point out that he had not read the instructions.  No.  Did it help to say that he should have exported the registry first?  No it did not help at all.  Did it help that hundreds of visitors had successfully modified their registries?  Actually – yes.  This thought stopped me from removing the pages.  The lesson is for me to make my instructions even clearer and perhaps give out a few more warnings.

Incidentally, in a former life when I was a teacher, an unknown pupil stole a magnet from the science lab.  The rest of the teachers said that we (we = Guy) should keep the whole class behind until someone owned up, however I did not like that strategy.  I refused then, just as a refuse now, to punish the innocent majority by removing pages which are helpful provided they are used with care.  It’s not fair to deprive the blameless majority just because one or two people don’t do the right thing.

The relevance of my anecdote to this ezine is that I have a script, which with a simple modification, could delete all your Active Directory users (except the Administrator and the Guest).  My message to you is this – with scripts which delete, take extra care before you slavishly copy and paste.

This Week’s Mission

Here is a scenario suitable for a deletion script.  It’s the end of the academic year and 2,000 students have just left your campus.  Our mission is to identify these users and then delete their Active Directory accounts.  If there is a weakness in this article it’s not emphasising the need for testing appropriate criteria for selecting the accounts to delete.

Delete Accounts -v- Disable Accounts

While this ezine is about deleting accounts, where possible I favour disabling accounts rather than deleting them.  To make up your own mind try these simple experiments, preferably in a test domain.

Action:  Try this, disable about 2,000 unwanted accounts.  Feedback, does anything bad happen?  OK. now try this: Delete those 2,000 accounts, does anything good happen, e.g. Active Directory runs faster, the NTDS.dit file is significantly smaller.  From analysing your results, you are in a position to judge what to do in future, whether to delete or to disable user accounts that are no longer needed.

Additional Note from A. M. Ginsberg (and others).  When you delete an Active Directory account, you need to delete Home directories and possibly roaming profiles.  Deleting those files is a separate project.

Guy Recommends:  SolarWinds’ Free Bulk Import ToolFree Download Solarwinds Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD’s attributes, click and import the users.

Optionally, you can provide the name of the OU where the new accounts will be born. Download your FREE bulk import tool.

If you need more comprehensive software, download a free trial of SAM (Server & Application Monitor)

VBScript Strategy

From a scripting strategy, the mission requires the following elements:

  • Connecting to Active Directory
  • Locking-on to the specific OU
  • Initiating the for-next loop
  • Adding a filtering criteria (Optional, but highly recommended)
  • Crucially, adding this delete statement: objOU "user", cn=name
  • Finally, tidying up and exiting gracefully

To add yet more words of caution, even if the ultimate goal was delete a bunch of users, I would begin by merely disabling their accounts.  If I got it wrong and disabled the wrong accounts, then at least I could reverse the command and enable those users.  Disabling accounts is covered elsewhere, however, the key property is UserAccountControl and the key value is 514 (not 512).

It gives me even more glee than usual to practice my strategy of building scripts gradually.  In this specific example, points 1 and 2 are a digression, but they are worth it from the safety point of view.
1) Experiment with Contact objects, before you move on to User objects.
2) Change the Description property, just so that we are sure that the script is doing what we planned.
3) Ok let’s delete the users.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

Example 1 – VBScript to Modify the Description Property

The goal here is to modify the description of all the Contact objects in a named OU.  Once you understand this script, then I declare that you are ready to substitute Users for Contacts and also to substitute delete object for modify properties.

Pre-requisites

  1. In your Active Directory domain you need to create an OU called Contacts.  Alternatively you could amend this command:
    strContainer = "OU=Contacts, "
  2. You need to populate the Contacts OU with at least one contact and at least one user account.
  3. Note a good VBScript editor will help you identify VBScript methods and properties.  Get your free trial of OnScript

 

Instructions

  1. Save the following script to a text file with a .vbs extension, for example: C: \Script\ContactProperty.vbs.
  2. Navigate to the folder where you saved the .vbs file. 
  3. Double click to execute the file
  4. Launch Active Directory Users and Computers to check the effects.
  5. Beware of the refresh problem.  Pressing F5 is not good enough, right-click the OU and select ‘Refresh’ from the short cut menu.
     
‘ ContactProperty.vbs
‘ Sample VBScript modify the description property of a contact
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 2.1 – July 2007
‘ ————————————————————‘
Option Explicit
Dim objOU, objUser, objRootDSE
Dim strContainer, strDescription, strObject, strDNSDomain
‘ Bind to Active Directory Domain
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
strDescription ="I’m Guy’s Contact"
strObject = "contact"
‘ ————————————————————-‘
‘ Important create OU=Contacts or change value for strContainer
‘ ————————————————————-‘
strContainer = "OU=Contacts, "
strContainer = strContainer & strDNSDomain
set objOU =GetObject("LDAP://" & strContainer)
For each objUser in objOU
    If objUser.class= strObject then
       ‘ The heart of this script – Modify object
       objUser.Put "description", strDescription
       objUser.SetInfo
    End if
next
set objUser = Nothing
‘ End of VBScript
 

Learning Points

Note 1:  I admit that modifying a contact is a diversion from our mission to delete users.  My reasoning is example 1 represents a safe stage where you can acclimatise yourself with connecting to active directory, and locking on to a particular OU.

Note 2:  To increase the power and the scope of this script you could add code which ‘Walks’ the active directory tree.  What I mean is add extra looping which modifies contacts (or deletes users) in all OUs.  See ezine 124 for ‘Walking the Active Directory Tree".  However, before you extend the scope of your script, you would be mad if you did not spend time perfecting a criteria.  For example, add code so that you only deleted user accounts whose Description said "Class of 1999".  I said mad not to add a filter, because without such criteria a universal script would delete every user apart from the Administrator and the Guest – you have been warned! 

Note 3:  I should have mentioned it before, but if you are working with live accounts as opposed to a test network, then you should backup Active Directory before trying this script.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Orion performance monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Example 2 – VBScript to Delete Contact Object

Before we delete the users and fulfil our mission, I would like to continue practicing on contact objects.  In fact, once you master this script then you can edit strObject = "contact" to strObject ="user".  Note that each is singular. 

‘ ContactDelete .vbs
‘ Sample VBScript to delete contacts in a named OU
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 2.1 – July 2007
‘ ————————————————————‘
Option Explicit
Dim objOU, objUser, objRootDSE, strCN
Dim strContainer, strDescription, strObject, strDNSDomain
‘ Bind to Active Directory Domain
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
strDescription ="I’m Guy’s Contact"
strObject = "contact"
‘ ————————————————————-‘
‘ Important create OU=Contacts or change value for strContainer
‘ ————————————————————-‘
strContainer = "OU=Contacts, "
strContainer = strContainer & strDNSDomain
set objOU =GetObject("LDAP://" & strContainer)
For each objUser in objOU
   If objUser.class= strObject then
       ‘ The heart of this script – delete contact
       strCN = "CN=" & objUser.cn
       objOU.delete strObject, strCN
   End if
next
set objOU = Nothing
‘ End of VBScript

 

Learning Points

Note 1:  The crucial line that actually does the deleting is:
objOU.delete strObject, strCN

Observe the two arguments strObject – type of object, and the name of the object to delete.

Note 2:  Trace how the script creates the syntax for the common name (CN=)

Note 3:  My biggest stumbling block in the whole script was realizing that I needed objOU.delete and not objUser.delete.

Example 3 – VBScript to Delete All Users in a Named OU

Do be careful.  This script is designed to delete user accounts in an Active Directory domain.  In fact, I originally thought to omit this script and leave you with just Example 2.  My thinking was, if you were able to deduce how to amend the code in example 2, then there was little danger of you wrecking your own Active Directory.  Eventually, for the sake of completeness, I relented and here is the script that actually deletes user accounts.

‘ UserDelete .vbs
‘ Sample VBScript to delete users in a named OU
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 2.1 – July 2007
‘ ————————————————————‘
Option Explicit
Dim objOU, objUser, objRootDSE
Dim strContainer, strCN, strObject, strDNSDomain
‘ Bind to Active Directory Domain
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
strObject = "user"
‘ ————————————————————-‘
‘ Important create OU=Contacts or change value for strContainer
‘ ————————————————————-‘
strContainer = "OU=Contacts, "
strContainer = strContainer & strDNSDomain
set objOU =GetObject("LDAP://" & strContainer)
For each objUser in objOU
   If objUser.class= strObject then
       ‘ The heart of this script – delete object
       strCN = "CN=" & objUser.cn
       objOU.delete strObject, strCN
   End if
next
set objOU = Nothing
‘ End of VBScript

 

 

Note 0: A good VBScript editor will help you identify VBScript methods and properties.  Get your free trial of OnScript

Note 1:  Study the syntax of this line:
objOU.delete strObject, strCN

Observe the two arguments strObject – type of object, and the CN of the object to delete.

Note 2:  Understand how the script loops, during the loop it obtains the CN of the user, then deletes that account!  Then it goes on and deletes the next account, and the next….

Note 3:  My biggest stumbling block in when creating this script was realizing that I needed objOU.delete and not objUser.delete.

Summary of Deleting User Accounts in Active Directory

Deleting users, rather like capital punishment, should be an action of last resort.  Indeed, just as there are those who oppose capital punishment on principle, there are respected consultants who say you should never delete Active Directory accounts, instead you should disable objects that are no longer required.

If you are going to kill off some of your users, be sure you choose the correct criteria.  Take steps to prevent your script getting out of control, you probably don’t want mass destruction of all your users!

See More Active Directory VBScripts to Create Users

• User Spreadsheet  • Ezines  •LDAP Properties  • ADSIEdit  • Free Solarwinds CSV Import Tool

Ezine 13 Create Users  • Ezine 21 Create Users  • Ezine 23 Enable Accounts  •Ezine 93 ADSIEdit

Ezine 134 Delete Users  • VBScript create users  •PowerShell Get Users  •PowerShell Create Users