'This script disables users that have not logged on within 35 days, that are not currently disabled, do not have non-expiring passwords and then generates a new log file every time the script is run in the format of MM_DD_YYYY HH-MM-SS.txt
option Explicit
Dim adoCommand, adoConnection, strBase, strFilter, strAttributes
Dim objRootDSE, strDNSDomain, strQuery, adoRecordset, strDN, objUser
Dim dtmDate, strDate
Dim strFile, objFSO, objFile
Dim temp, temp1
' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
'Search entire Active Directory domain.
strBase = "<LDAP://" & strDNSDomain & ">"
'Determine date, in GeneralizedTime format, 35 days in the past.
dtmDate = DateAdd("d", Now(), -35)
strDate = CStr(Year(dtmDate)) & Right("0" & Cstr(Month(dtmDate)), 2) & Right("0" & CStr(Day(dtmDate)), 2) & "000000.0Z"
'Filter on user objects that have not logged on within 35 days, are not disabled and do not have non-expiring passwords.
strFilter = "(&(objectCategory=person) (objectClass=user)" & "(lastLogonTimeStamp<= " & strDate & ")" & "(!lastLogonTimeStamp=0)" _
& "(!userAccountControl:1.2.840.113556.1.4.803:=2)" & "(!userAccountControl:1.2.840.113556.1.4.803:=65536))"
' Comma delimited list of attribute values to retrieve.
strAttributes = "distinguishedName"
' Construct the LDAP syntax query.
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
'Run the query
Set adoRecordset = adoCommand.Execute
'Generate the filename in the format MM_DD_YYYY HH-MM-SS.txt
'remote / and : from filename current date
temp=replace((CStr(Now())), "/", "_")
temp1=replace(temp, ":", "-")
'create the file
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\scripts\" & temp1 & ".txt")
'Enumerate the resulting recordset.
objFile.WriteLine "Program run at: " & CStr(Now())
Do Until adoRecordset.EOF
'Retrieve values.
strDN = adoRecordset.Fields("distinguishedName").Value
'Escape any "/" characters.
strDN = Replace(strDN, "/", "\/")
'Bind to user object.
Set objUser = GetObject("LDAP://" & strDN)
'Disable the account
objUser.AccountDisabled = True
'Save changes to AD.
objUser.SetInfo
'Log information.
objFile.WriteLine "User disabled: " & strDN
'Move to the next record in the recordset.
adoRecordset.MoveNext
Loop
'Clean up.
objFile.Close
adoRecordset.Close
adoConnection.Close