
Option Explicit
 
Const REPORT_FILE = "Users.csv"
 
Const ADS_SCOPE_SUBTREE = 2
Const ADS_UF_ACCOUNTDISABLE = 2
 
Dim objFileSystem, objFile, objConnection, objCommand, objRootDSE, objRecordSet
Dim strUsername, strFirstname, strLastname, strEmail
Dim intUAC
 
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile(REPORT_FILE, 2, True, 0)
 
objFile.WriteLine "AD Username,First Name,Last Name,E-mail"
 
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
 
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
 
Set objRootDSE = GetObject("LDAP://RootDSE")
objCommand.CommandText = "SELECT sAMAccountName, userAccountControl, givenName, sn, mail " &_
	"FROM 'LDAP://" & objRootDSE.Get("defaultNamingContext") &_
	"' WHERE objectClass='user' AND objectCategory='person'"
Set objRootDSE = Nothing
 
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Timeout") = 600
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
 
While Not objRecordSet.EOF
 
	intUAC = objRecordSet.Fields("userAccountControl")
 
	If intUAC And ADS_UF_ACCOUNTDISABLE Then
		' Account is Disabled, ignore it.
	Else
			On Error Resume Next
			strUsername = "" : strUsername = objRecordSet.Fields("sAMAccountName")
			strFirstname = "" : strFirstname = objRecordSet.Fields("givenName")
			strLastname = "" : strLastname = objRecordSet.Fields("sn")
			strEmail = "" : strEmail = objRecordSet.Fields("mail")
			On Error Goto 0
			
			objFile.WriteLine strUsername & "," & strFirstname & "," & strLastname & "," & strEmail
	End If
 
	objRecordSet.MoveNext
Wend
 
objConnection.Close
 
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing
