…and it works great!
Change the OU on line 7 to your OU and run for each OU that contains users.
This redirects the output to a csv file.
Run the script like this:
cscript email.vbs > email.csv
‘===============================
Option Explicit
Dim objRootDSE, strDNSDomain, objCommand, objConnection
Dim strBase, strFilter, strAttributes, strQuery, objRecordSet
Dim strNTName, strDN, colmail, strmail, stremail, strOU
StrOU = “OU=YourOU,”
‘ Determine DNS domain name.
Set objRootDSE = GetObject(“LDAP://RootDSE”)
strDNSDomain = objRootDSE.Get(“defaultNamingContext”)
‘ Use ADO to search Active Directory.
Set objCommand = CreateObject(“ADODB.Command”)
Set objConnection = CreateObject(“ADODB.Connection”)
objConnection.Provider = “ADsDSOObject”
objConnection.Open “Active Directory Provider”
objCommand.ActiveConnection = objConnection
‘ Search entire domain.
strBase = “”
‘ Filter on contacts
strFilter = “(&(&(& (mailnickname=*)(| (&(objectCategory=person)(objectClass=user))))))”
‘ Comma delimited list of attribute values to retrieve.
strAttributes = “cn,distinguishedName,adspath,proxyaddresses”
‘ Construct the ADO query, using LDAP syntax.
strQuery = strBase & “;” & strFilter & “;” & strAttributes & “;subtree”
‘ Run the query.
objCommand.CommandText = strQuery
objCommand.Properties(“Page Size”) = 100
objCommand.Properties(“Timeout”) = 30
objCommand.Properties(“Cache Results”) = False
Set objRecordSet = objCommand.Execute
‘ Enumerate the recordset and output the values retrieved in
‘ comma delimited format.
Do Until objRecordSet.EOF
strNTName = objRecordSet.Fields(“cn”).Value
strDN = objRecordSet.Fields(“distinguishedName”).Value
colmail = objRecordSet.Fields(“proxyAddresses”)
If IsEmpty(colMail) Then
‘ The attribute is empty (has no values).
wscript.echo “No Email address”
Else
‘ The attribute has one or more values – enumerate.
For Each strMail In colMail
If Instr(strMail, “SMTP:”) then
strEmail = Right(strMail, Len(strMail)-5)
End If
Next
End If
Wscript.Echo strNTName & “,” & strEmail
objRecordSet.MoveNext
Loop
objRecordSet.Close
‘ Clean up.
objConnection.Close
Set objRootDSE = Nothing
Set objCommand = Nothing
Set objConnection = Nothing
Set objRecordSet = Nothing
‘===============