Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / VBScript

VBScript to Disable Old Accounts in Active Directory

Rate me:
Please Sign up or sign in to vote.
3.30/5 (7 votes)
4 Sep 2007CPOL2 min read 104.5K   1.5K   12   13
Searches a given OU for all users that haven't logged on in a given length of time. Then gives you the option to disable them and move them to a new folder.

Introduction

This script is basically used to search out and disable stale accounts. The code is fairly straightforward but uses a combination of the LDAP, WinNT and FSO to accomplish its goals. The attached document is a working script that should be run from an AD server while logged on as an administrator. All you need to do is enter your domain information in the variable declarations at the top. It will display a message asking if you want to disable the accounts and another message asking if you want to just save the output to a file.

Background

If your business is anything like mine, HR never tells you when a person is gone so running this script monthly can at least tell you when the last time they logged in was.

The Code

The main functions in this script are based off of ADSI and using the an LDAP object to query Active Directory. Since LDAP queries will only access a single Organizational Unit (OU), you have to recursively search all sub-folders in order to find all of the users.

First off, you need to set up a number of variables based off of your AD.

VBScript
bDisable = 0      
'do you want to disable and move the accounts?
strFileName = "c:\users.tab"  
'the file where the tab delimited results are saved
strUserDN = "servername/OU=All Users, dc=yourdomain, dc=com"  
'initial OU where the users are located
'you can leave out the servername/ if you only have 1 domain controller
strNewParentDN = "OU=Inactive Users, dc=yourdomain, dc=com"           
'location where disabled users are moved to
strDomain = "yourdomain.com" 
'FQDN
iDayThreshold = 180
'number of days without logging in

These two simple functions can recursively find all of the users.

VBScript
Function EnumOUs(sADsPath)
'recursively finds all of the OU's and users in the given AD path
Set oContainer = GetObject(sADsPath)
    oContainer.Filter = Array("OrganizationalUnit")
    For Each oOU in oContainer
        EnumUsers(oOU.ADsPath)
        EnumOUs(oOU.ADsPath)
    Next
End Function

Function EnumUsers(sADsPath)
'finds all of the users' last login time
Set oContainer = GetObject(sADsPath)
    oContainer.Filter = Array("User")
    For Each oADobject in oContainer
        strOut = strOut & oADobject.Name & vbCrLf
       'you can put other things here depending on what you want to do
    Next
End Function

This will basically build a string that has all of the users in it. However, instead of just building a string, we can also get the lastLogon property of each user. Once we have that, we can determine what we want to do with the users that haven't logged on in the given time frame.

Since the lastLogon property is saved as an integer in LDAP, you have to collect the data as an object and convert it to a usable date value.

VBScript
'for each user object, oADobject find the last logon
    Set objLogon = oADobject.Get("lastLogon")
    intLogonTime = objLogon.HighPart * (2^32) + objLogon.LowPart 
    intLogonTime = intLogonTime / (60 * 10000000)
    intLogonTime = intLogonTime / 1440
    intLogonTime = intLogonTime + #1/1/1601#
    inactiveDays = Fix(Now() - intLogonTime)

Based off whatever logic you choose, you can then disable the accounts or move them to an "inactive users" folder or both. This function will move the user, then disable it.

VBScript
Sub MoveUser(adsName, adsPath, adsSAM)
'adsName is the CN of the object - CN=Some Guy
'adsPath is the full DN path - LDAP://cn=Some Guy, 
'OU=All Users, DC=yourdomain, DC=com
'adsSAM is the unique object name (their username) - someguy
'moves the user from the given OU to a new OU
    Set objUser = GetObject("LDAP://" & strNewParentDN)
    objUser.MoveHere sPath, sName

'then disable the user
    Set objUser = GetObject("WinNT://" & strDomain & "/" & _
        oADobject.sAMAccountName)
    objUser.AccountDisabled = True
    objUser.SetInfo
End Sub

Then, we can also use a FSO save the list of users that were disabled to a file if you want. This function takes the output string and saves it to a file.

VBScript
Sub SaveToFile(strData)
'create a FSO
    Dim objFSO
    Set objFSO = CreateObject("Scripting.FileSystemObject") 
'if the file exists already open it for writing

    If objFSO.FileExists(strFileName) Then
        Set objTextStream = objFSO.OpenTextFile(strFileName, 2)
  
            objTextStream.Write strData
            objTextStream.Close
        Set objTextStream = Nothing
'otherwise, create the file and write the data
    Else
        Set objTextStream = objFSO.CreateTextFile(strFileName, True)  
            objTextStream.Write strData
            objTextStream.Close
        Set objTextStream = Nothing
    End If
End Sub

Download a complete copy of the script here.

Points of Interest

I found various parts of this script on different web sites but never found anything to tie them all together. This combination of routines really gives some pretty good functionality for systems administrators to get rid of inactive users and to get a report on it too.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExcellent Pin
Jhon Drake25-Nov-14 23:35
Jhon Drake25-Nov-14 23:35 
Great article , thanks for sharing the script to disable old accounts in active directory environment. I tried an automated tool named Lepide Active Directory Cleaner (http://www.lepide.com/active-directory-cleaner/) . This tool helps to find out old computer accounts and generate report based on old user/computer accounts and manage and view the list of all inactive users, inactive or unused computers accounts, disabled users or computers accounts.
QuestionError Pin
pitpit25-Apr-12 0:31
pitpit25-Apr-12 0:31 
QuestionCode 80072030 - There is no such object on the server Pin
Member 872823530-Mar-12 21:57
Member 872823530-Mar-12 21:57 
Questionthis VB code Pin
dennylutz8025-Jul-11 17:39
dennylutz8025-Jul-11 17:39 
Generalrepotees in an organisation Pin
nicetohaveyou4-Nov-08 4:15
nicetohaveyou4-Nov-08 4:15 
QuestionButt is thouroughly kicked Pin
Steven Causey1-Aug-08 9:16
Steven Causey1-Aug-08 9:16 
AnswerRe: Butt is thouroughly kicked Pin
Steven Causey1-Aug-08 9:17
Steven Causey1-Aug-08 9:17 
GeneralRobert's question Pin
Genevieve Sovereign4-Sep-07 5:27
Genevieve Sovereign4-Sep-07 5:27 
GeneralRe: Robert's question Pin
Jesse Fatherree4-Sep-07 5:53
Jesse Fatherree4-Sep-07 5:53 
GeneralRe: Robert's question Pin
bbstone5-Sep-07 10:32
bbstone5-Sep-07 10:32 
GeneralRe: Robert's question Pin
Cenarkion4-Nov-07 16:16
Cenarkion4-Nov-07 16:16 
QuestionRe: Robert's question Pin
Coldfire27-Apr-08 23:41
Coldfire27-Apr-08 23:41 
GeneralRe: Robert's question Pin
BugMeNot ACCOUNT28-Feb-08 23:11
BugMeNot ACCOUNT28-Feb-08 23:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.