Need to extract some user account information from Active Directory

Posted on 2008-10-27
Last Modified: 2012-06-21
I am needing a VBScript to that will query a txt file of user names, and then create an output csv file containing the follwoing information from Active Directory about the users.

First Name
Last Name
Question by:seaninman
LVL 10

Expert Comment

ID: 22814227
Are all the users you need to look up in a single OU?

Author Comment

ID: 22814250
Sorry forgot to the put that.  No there are mulitiple OU's

Accepted Solution

Angelized earned 500 total points
ID: 22819875
Here we go, lemme know if you need me to comment this code.
'Option Explicit

Dim oFSO, ForReading, ForWriting, objdialog, Intresult, userfile

Dim Mylist, myarray, username, sUserLDAPName, ts, report

ForReading = 1

ForWriting = 2

Set oFSO=CreateObject("Scripting.FileSystemObject")

Set objDialog = CreateObject("UserAccounts.CommonDialog")

objDialog.Filter = "Text Files|*.txt|All Files|*.*"

objDialog.FilterIndex = 1

intResult = objDialog.ShowOpen

If intResult = 0 Then



    UserFile = objDialog.FileName

End If

MyList= ofso.OpenTextFile(UserFile, ForReading).ReadAll

myArray=Split(MyList,vbCrLf, -1, vbtextcompare)

For Each username In myarray 

	sUserLDAPName = QueryActiveDirectory(Trim(username))

	If sUserLDAPName <> "Not Found" Then

	   On Error Resume Next

	   Set objUser = GetObject("LDAP://" & sUserLDAPName) 

	   report = report & username

	   report = report & "," & CheckIfEmpty(objUser.Firstname)

	   report = report & "," & CheckIfEmpty(objUser.lastname)

	   report = report & "," & CheckIfEmpty(objUser.description)

	   report = report & "," & CheckIfEmpty(objUser.department)

	   report = report & vbCrLf

	End If  


Set ts = oFSO.CreateTextFile ("output.csv", ForWriting)

ts.Write report

MsgBox "Done!"


Function CheckIfEmpty (property)

  If IsEmpty(Property) Then 

     CheckIfEmpty = "N/a"


     CheckIfEmpty = property

  End if 

End Function

Function QueryActiveDirectory(sUsername)

'Function:      QueryActiveDirectory

'Purpose:       Search the Active Directory's Global Catalog for users

'Parameters:    UserName - user to search for

'Return:        The user's distinguished name


    Dim oAD 'As IADs

    Dim oGlobalCatalog 'As IADs

    Dim oRecordSet 'As Recordset

    Dim oConnection 'As New Connection

    Dim strADsPath 'As String

    Dim strQuery 'As String

    Dim strUPN 'As String

    Set oRecordSet = CreateObject("ADODB.Recordset")

    Set oConnection = CreateObject("ADODB.Connection")

    'Determine the global catalog path

    Set oAD = GetObject("GC:")

    For Each oGlobalCatalog In oAD

        strADsPath = oGlobalCatalog.ADsPath


    'Initialize the ADO object

    oConnection.Provider = "ADsDSOObject"

    'The ADSI OLE-DB provider

    oConnection.connectiontimeout = 15

    oConnection.Open "ADs Provider"

    'Create the search string

    'MsgBox strADsPath

    strQuery = "<" & strADsPath & _

      ">;(&(objectClass=user)(objectCategory=person)(samaccountName=" & _

      sUsername & "));userPrincipalName,cn,distinguishedName;subtree"

        'Execute the query

    'MsgBox strQuery

    Set oRecordSet = oConnection.Execute(strQuery)

    If oRecordSet.EOF And oRecordSet.BOF Then

       'An empty recordset was returned

        QueryActiveDirectory = "Not Found"

    Else    'Records were found; loop through them

        While Not oRecordSet.EOF

            QueryActiveDirectory = oRecordSet.Fields("distinguishedName")



    End If


    Set oConnection = Nothing

    Set oRecordSet = Nothing

End Function

Open in new window


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Exe program is not a valid Win 32 application 15 107
Novice question on VBScript 8 53
Scraping specific data within an XML document 19 54
Running Visio Macro from VBS File 3 59
In this article we want to have a look at the directory attributes which are used by Microsoft to store the so called Security Identifiers (SID). These SIDs plays an important role in delegating and granting permissions and in authentication of trus…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: (…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now