如何在不知道确切OU的情况下进行LDAP查询

时间:2014-11-17 19:47:59

标签: vbscript ldap

Set objDomain = GetObject("WinNT://abc.local")

For each objDomainItem in objDomain

    if objDomainItem.Class = "User" then

        'WScript.echo "Name: " & objDomainItem.Name + " : Full Name: " + objDomainItem.FullName

        Set objUser = Nothing
        err.clear

        Set objUser = GetObject("LDAP://cn=" & objDomainItem.FullName & ",OU=IS, OU=Users, OU=ABC Company, DC=ABC, dc=local")

        if err.number = 0 then
            wscript.echo "distinguishedName: " & objUser.distinguishedName
        end if


    end if


Next

现在,这可以很好地列出IS部门中的所有用户(OU = IS)。但当我拿出“OU = IS”列出所有部门的所有用户时,它什么都不返回;完全没有用户对象。它将返回给定fullName的用户对象的唯一方法是,如果我还指定包含该用户的OU;但是我没有供应它的OU。

我们的AD结构是

ABC Company --> Users --> IS
ABC Company --> Users --> FINANCE
ABC Company --> Users --> Management
ABC Company --> Users --> Flight Operations
etc etc etc

我想使用上面的代码从“用户”级别向下遍历所有部门的所有用户,但是,一旦我删除“OU = IS”,它就不会返回任何内容。

任何帮助?

1 个答案:

答案 0 :(得分:1)

使用SubtreeADODB.Connection对象执行范围ADODB.Command的查询:

base  = "<LDAP://OU=Users,OU=ABC Company,DC=ABC,DC=local>"
fltr  = "(&(objectClass=user)(objectCategory=Person))"
attr  = "distinguishedName,sAMAccountName"
scope = "subtree"

Set cn = CreateObject("ADODB.Connection")
cn.Provider = "ADsDSOObject"
cn.Open "Active Directory Provider"

Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
cmd.CommandText = base & ";" & fltr & ";" & attr & ";" & scope

Set rs = cmd.Execute
Do Until rs.EOF
  WScript.Echo rs.Fields("distinguishedName").Value
  WScript.Echo rs.Fields("sAMAccountName").Value
  rs.MoveNext
Loop

根据需要向attr添加其他属性(该变量包含属性名称列表,以逗号分隔的字符串形式)。

由于这些查询每次都需要相同的样板代码,我厌倦了一段时间以前一遍又一遍地编写它并将其包装在自定义类(ADQuery)中以简化其用法:

'<-- paste or include class code here

Set qry = New ADQuery
qry.SearchBase = "OU=Users,OU=ABC Company,DC=ABC,DC=local"
qry.Attributes = Array("distinguishedName", "sAMAccountName")

Set rs = qry.Execute
Do Until rs.EOF
  WScript.Echo rs.Fields("distinguishedName").Value
  WScript.Echo rs.Fields("sAMAccountName").Value
  rs.MoveNext
Loop