Query Active Directory and Export using VBScript/WSH


I want to query a AD server to get certain fields using VBScript or WSH script

These fields

  • DN
  • userid
  • mail
  • company
  • displayName

And export/output the fields to a text file.

How can I accomplish that?

I came from linux background and need this as the computer that will run the script is running windows

Using linux,

`ldapsearch -x -h hostserver -b "cn=contacts,dc=support,dc=com" CN="name"`

Best Solution

The usual method is to use ADO and an LDAP query to retrieve information about AD objects:

Set rootDSE = GetObject("LDAP://RootDSE")

base   = "<LDAP://" & rootDSE.Get("defaultNamingContext") & ">"
filter = "(&(objectClass=user)(objectCategory=Person))"
attr   = "distinguishedName,userid,mail,company,displayName"
scope  = "subtree"

Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "Active Directory Provider"

Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = base & ";" & filter & ";" & attr & ";" & scope

Set rs = cmd.Execute
Do Until rs.EOF
  'do stuff with rs.Fields(fieldname).Value


As you can see there is a lot of boilerplate code involved, so I wrote this class (ADQuery) to simplify the handling. The README contains some examples.

If you already know the distinguished name of an object you can also directly retrieve it like this:

dn = "CN=Joe User,OU=Users,DC=example,DC=com"
Set user = GetObject("LDAP://" & dn)
WScript.Echo user.Get("displayName")
WScript.Echo user.Get("mail")