Oct 132011
 

Recently I’ve had to pull out sites and subnets from AD in order to match an IP Address against the subnet that I pulled out to determine whether a workstation is in that site.
I ran into some issues trying to do it in JScript because for some strange reason, the Description attribute for all the subnets is an array, so I had to convert it from a VB array to a Javascript array.

Now, onto the code I used –

First up, is setting up the ADO Connection.

var objRootDSE = GetObject("LDAP://RootDSE");
var strDomain = objRootDSE.Get("configurationNamingContext");
var objConnection = new ActiveXObject("ADODB.Connection");
objConnection.Provider="ADsDSOObject";
objConnection.Open("ADs Provider");
var objCommand = new ActiveXObject("ADODB.Command");
objCommand.ActiveConnection = objConnection;

All that does is setup the connection to AD and open up the connection using the ADs Provider.

Next up, is to run the query which will return all the Subnets within AD.

var Dom = "LDAP://CN=subnets,CN=Sites,"+strDomain;
objCommand.CommandText = "select cn,Name,Location,Description from '"+Dom+"'";
objSiteRecordSet = objCommand.Execute();

This will return a recordset with all subnets and their descriptions and locations.

After that, a simple case of enumerating the recordset to get what we need out of it.
In this example, I have returned just Name and Description, which means that in the earlier query, I needn’t have query all 4 attributes.

while(!(objSiteRecordSet.EoF)) {
var Desc = '';
var IPRange = objSiteRecordSet.Fields('Name').Value;
var Desc = objSiteRecordSet.Fields('Description').Value;
if(Desc == null) {
Desc = IPRange;
} else {
Desc = VBArray(Desc).toArray();
}
var result = [IPRange,Desc];
arrSites.push(result);
objSiteRecordSet.MoveNext;
}

In that code, the results are pushed into the arrSites array to be used elsewhere or to be returned depending on what you’re doing with the data.

Share