May 232011

Hi All,

The last few posts I’ve posted used the SQL syntax method to query Active Directory.
This is different to my previous posts where I was using the IADs interface.
With the IADs interface, we would bind to an object and query it that way, with ActiveX Data Objects, we use SQL-like syntax to query Active Directory

This codeblock below will select all users from the domain.

objRootDSE = GetObject("LDAP://RootDSE");
strDomain = objRootDSE.Get("DefaultNamingContext");
/*This gets the Default Naming context, i.e. the domain root*/

objConnection = new ActiveXObject("ADODB.Connection");
objConnection.Open("ADs Provider");
objCommand = new ActiveXObject("ADODB.Command");
objCommand.ActiveConnection = objConnection;

/*This sets up the Connection to AD, sets the provider to ADsDSOObject, and creates an object that we can use to execute a command*/

var strDom = "LDAP://"+strDomain;
/* The strDom string will later become part of the SQL command that we will execute. If you want to specify a OU or CN to search, here would be the place to put it. */

objCommand.CommandText = "select name from '"+strDom+" WHERE objectCategory = 'user'';

/* Next up is the command itself.*/

objRecordSet = objCommand.Execute();

/* Then we execute the command */
/* Once executed, the command will return an enumeration of the results.*/
/* We will use the standard JS enumeration methods here to get what we need*/

while(!(objRecordSet.EoF)) {
objRecordSet.Fields("name").value; // This will be the fields that you Selected in the command's value, if you've selected more than one then you will need a loop or multiple statements to get it all.

The codeblock will need modification to suit your needs but it well let you search Active Directory with ease from JScript.

SQL Dialect
Searching with ActiveX Data Objects (ADO)
Active Directory Services Data Services Objects