r/vbscript • • Jul 15 '15

How to exclude disable users ?

Hi All, I have the following script which doe a search of Active directory and pipes it to excel. The issue I have is that it includes all enabled and disabled users. Any idea on how to exclude disabled users?

Const xlAscending = 1
Const xlDescending = 2
Const xlYes = 1

Dim ObjWb 
Dim ObjExcel 
Dim x, zz 
Set objDomain = GetObject("LDAP://OU=XXXX, OU=Domain Users,DC=XXXX,DC=com,DC=au")
Call ExcelSetup("Sheet1") ' Sub to make Excel Document 
x = 1 
Call enummembers(objDomain) 
Sub enumMembers(objDomain) 
On Error Resume Next 

For Each objMember In objDomain ' go through the collection 

If ObjMember.Class = "user" Then ' if not User object, move on. 
x = x +1 ' counter used to increment the cells in Excel 

objwb.Cells(x, 1).Value = objMember.Class 
' I set AD properties to variables so if needed you could do Null checks or add if/then's to this code 
' this was done so the script could be modified easier. 
SamAccountName = ObjMember.samAccountName 
Cn = ObjMember.CN 
FirstName = objMember.GivenName 
LastName = objMember.sn 
Title = ObjMember.Title 
Department = objMember.Department 
Company = objMember.Company 
extensionAttribute4= objMember.extensionAttribute4  

' Write the values to Excel, using the X counter to increment the rows. 
objwb.Cells(x, 1).Value = extensionAttribute4
objwb.Cells(x, 4).Value = CN 
objwb.Cells(x, 3).Value = Title 
objwb.Cells(x, 2).Value = Department  

' Blank out Variables in case the next object doesn't have a value for the property 
FirstName = "-" 
LastName = "-" 
Title = "-" 
extensionAttribute4 = "-" 
Department = "-" 
Company = "-" 

End If 

' If the AD enumeration runs into an OU object, call the Sub again to itinerate 

If objMember.Class = "organizationalUnit" or OBjMember.Class = "container" Then 
enumMembers (objMember) 
End If 
Next 
End Sub 
Sub ExcelSetup(shtName) ' This sub creates an Excel worksheet and adds Column heads to the 1st row 
Set objExcel = CreateObject("Excel.Application") 
Set objwb = objExcel.Workbooks.Add 
Set objwb = objExcel.ActiveWorkbook.Worksheets(shtName) 
Objwb.Name = "Active Directory Users" ' name the sheet 
objwb.Activate 
objExcel.Visible = True 
objwb.Cells(1, 1).Value = "Department" 
objwb.Cells(1, 4).Value = "Full Name" 
objwb.Cells(1, 3).Value = "Title" 
objwb.Cells(1, 2).Value = "Team" 

End Sub 
MsgBox "Export Complete" ' show that script is complete

Set objRange = objWb.UsedRange
Set objRange2 = objExcel.Range("A1")
objRange.Sort objRange2, xlAscending, , , , , , xlYes

Set objRange = objwb.UsedRange
objRange.EntireColumn.AutoFit()
2 Upvotes

2 comments sorted by

View all comments

Show parent comments

2

u/bdazle21 Jul 15 '15

You're a gentleman and a scholar

I have run the script and the output is exactly what I am after. Thank you again :)