Saturday, April 18, 2009

Example AD LDAP Queries for When You Really Get Bored

Stuck inside on a rainy day? I'm indoors on probably THE most beautiful day of the year, and it's a Saturday. I must be a complete idiot. Ok, one post and I'm outdoors the rest of the day, I promise.

Here is a chunk of code you can use, abuse, misuse (all warrantees voided, disclaimers disclaimed, liabilities denied, etc. etc.) dissect, bisect, and resect if you really want. I hope it doesn't need explanation.


Const strDN = "dc=contoso,dc=local"

q1 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='computer'"
q2 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='computer' AND operatingSystem <> 'Windows*Server*'"
q3 = "SELECT * FROM 'LDAP://[DN]' WHERE objectCategory='person'"
q4 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='organizationalUnit'"
q5 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='container'"
q6 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='group'"
q7 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='computer' AND operatingSystem = 'Windows*XP*'"
q8 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='computer' AND operatingSystem = 'Windows*Vista*'"
q9 = "SELECT * FROM 'LDAP://[DN]' WHERE objectClass='computer' AND operatingSystem = 'Windows*7*'"

selectQuery = q7

'----------------------------------------------------------------

strQuery = Replace(selectQuery, "[DN]", strDN)

Const ADS_SCOPE_SUBTREE = 2

On Error Resume Next
Set objConn = CreateObject("ADODB.Connection")
Set objCmd = CreateObject("ADODB.Command")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
Set objCmd.ActiveConnection = objConn

objCmd.CommandText = strQuery

objCmd.Properties("Page Size") = 1000
objCmd.Properties("Timeout") = 30
objCmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCmd.Properties("Cache Results") = False
Set objRs = objCmd.Execute
If Err.Number <> 0 Then
Set objShell = Nothing
Wscript.Echo "error: " & Err.Number & " - " & Err.Description
Wscript.Quit
End If
objRs.MoveFirst

If objRs.BOF and objRs.EOF Then
Wscript.Echo "no records found"
Else
Do Until objRs.EOF
For i = 0 to objRs.Fields.Count-1
Wscript.Echo objRs.Fields(i).Value
Next
objRs.MoveNext
Loop
End If

objRs.Close
objConn.Close
Set objRs = Nothing
Set objCmd = Nothing
Set objConn = Nothing

No comments: