Showing posts with label ldap. Show all posts
Showing posts with label ldap. Show all posts

Tuesday, July 6, 2010

LDAP query

I needed to find out how to query the active directory database easily and so looked into how to script an LDAP query. Code below shows the basics of the simple query based on the LDAP://rootdse object and a recordset connection to perform the query.

Function LDAPsearch (strSearch,strQ)
'set variable to hold required amount of attributes
Dim aResults(4)

'set LDAP defaults to root domain
Set rootDSE = GetObject("LDAP://RootDSE")
DomainContainer = rootDSE.Get("defaultNamingContext")

'create recordset connection
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADSDSOObject"
conn.Open "ADs Provider"

'set query, using strQ for searched FOR item and strSearch as search ON string
ldapStr = ";(" & strQ & "=" & strSearch & "*);adspath;Subtree"

'execute LDAP query
Set rs = conn.Execute(ldapStr)

'look for records that meet the query
While Not rs.EOF

'FoundObject is a successful find for query
Set FoundObject = GetObject (rs.Fields(0).Value)

'put results into array with tags
aResults(0) = FoundObject.employeeID
aResults(1) = FoundObject.displayName
aResults(2) = FoundObject.userPrincipalName
aResults(3) = FoundObject.sAMAccountName
aResults(4) = FoundObject.telephoneNumber

'goto next record
rs.MoveNext

'concatenate attributes to string
For i = 0 To 4
strResult = strResult & aResults(i)
Next

'count results (searches may produce multiple results)
iCount = iCount + 1

'add newline results string
strResult = strResult & vbnewline

'continue until no further records are found
Wend
End Function