How can I create a file that contains the usernames and email addresses for a specific organizational unit (OU) or Container?

A. The following script, which you can download here, outputs to file with a pipe (|) delimiter a user's given name, surname (sn), and email address. This output file can then be read into a Microsoft Excel spreadsheet with the pipe set as the delimiter for cell-based access to the data.

Option Explicit

Dim strFilePath, strLdapPath, objFSO, objFile, objConnection, objChild

' Check all arguments required have been passed
If Wscript.Arguments.Count   required. For example:" & vbCrLf _
& "cscript listuserswithemail.vbs ou=test,dc=demo,dc=test c:\User.txt"   
End If

strLdapPath = Wscript.Arguments(0)

strFilePath = Wscript.Arguments(1)

Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open the file for write access.
On Error Resume Next
Set objFile = objFSO.OpenTextFile(strFilePath, 2, True, 0)
If Err.Number  0 Then
On Error GoTo 0
Wscript.Echo "File " & strFilePath & " cannot be opened"
End If
On Error GoTo 0

Set objConnection = GetObject("LDAP://" & strLdapPath)
objConnection.Filter = Array("user")

For Each objChild In objConnection
WScript.Echo objChild.Name & vbTab & objChild.givenName & " " _
  & & " " & objChild.mail 
objFile.WriteLine objChild.givenName & "|" & & "|" & objChild.mail

' Close file connection

Wscript.Echo "Operation Completed"

Run the script using the following command: D:\Temp>cscript listuserswithemail.vbs "ou=justice league,dc=savilltech,dc=com" listuserswithemail.txt The script produced this output when run on my system: CN=Arthur Curry Arthur Curry [email protected]
CN=Barry Allen Barry Allen [email protected]
CN=Bruce Wayne Bruce Wayne [email protected]
CN=Wally West Wally West [email protected]

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.