Archive

Archive for June, 2009

VB Query Active Directory Objects

June 13th, 2009 No comments

In an Active Directory environment there is often a requirement to query objects within the AD  database, either returning selected attribute values or using this information to for further queries.

The same principles apply across any object type, the script below connects via LDAP, performs a query and returns selected values from Active Directory.

The below script will query all objects in the OU MyServers and subtree, in the domain Domain.co.uk, of type computer, returning the attributes Name and Location.

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject(”ADODB.Connection”)
Set objCommand = CreateObject(”ADODB.Command”)
objConnection.Provider = “ADsDSOObject”
objConnection.Open “Active Directory Provider”

Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = “Select Name, Location from ‘LDAP://OU=MyServers,DC=Domain,DC=co,DC=uk’ ” & “Where objectClass=’computer’”
objCommand.Properties(”Page Size”) = 1000
objCommand.Properties(”Searchscope”) = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF

‘ Insert Operators here
objRecordSet.MoveNext

Loop

Once the query has been run the results can then be used for any requirement, a simple example below is to display  the name of the computer followed by the Location attribute stored in AD.

……
Do Until objRecordSet.EOF

‘ Insert Operators here
Wscript.Echo “Computer Name: ” & objRecordSet.Fields(”Name”).Value
Wscript.Echo “Location: ” & objRecordSet.Fields(”Location”).Value

objRecordSet.MoveNext
Loop

Any attribute of the object can be displayed as long as it was requested in the initial query; Select Name, Location from…. , attribute names are LDAP attributes rather than field names seen in the Active Directory Users and Computers mmc. A list of attributes can be found here; Active Directory LDAP Attributes

One way to enhance this script further is for each computer selected perform a WMI query against it; VB WMI Query