通过sAMAccountName VBA查找用户

时间:2015-01-28 15:38:09

标签: vba excel-vba active-directory ldap ldap-query

我试图通过他们的sAMAccountName在AD中找到用户。这是我的代码:

sQuery = "<LDAP://OU=theOU,DC=mainDC,DC=com>;(&(objectClass=user)(objectCategory=Person)(sAMAccountName=sAMA));distinguishedName,sAMAccountName;subtree"

我按

执行此查询
Dim conn As New ADODB.Connection
Dim rs As ADODB.Recordset
conn.Open _
"Data Source=Active Directory Provider;Provider=ADsDSOObject"
Set rs = conn.Execute(sQuery)

查询没有失败。我也尝试将查询更改为:

<LDAP://OU=theOU,DC=mainDC,DC=com>;(&(objectClass=user)(objectCategory=Person)(sAMAccountName=sAMA));subtree

但也失败了。

我在VBA中这样做,非常感谢任何帮助!

我得到的错误是:

A referral was returned from the server.

此外,除了查询两次以外,还有更简单的方法来搜索多个域吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

找到这个片段,试一试。更改第1行的AD和第2行的sAMA:

StartNode = "cn=Users,dc=fabrikam,dc=com" 'edit with your values
strAccount = "HMustermann" 'edit with your searchvalue

Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
SearchScope = "subtree"

FilterString = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & strAccount & "))"
Attributes = "adspath"

LDAPQuery = "<LDAP://" & StartNode & ">;" & FilterString & ";" _
        & Attributes & ";" & SearchScope

objCommand.CommandText = LDAPQuery
objCommand.Properties("Page Size") = 1500
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False

Set objRecordset = objCommand.Execute

If Not objRecordset.EOF Then
   objRecordset.MoveFirst

   Do Until objRecordset.EOF
      strUserPath = objRecordset.Fields("ADsPath").Value
      Set objUser = GetObject(strUserPath)
      '-------get attributes -----------
      MsgBox objUser.DisplayName
      '--------------------------------------
      objRecordset.MoveNext
   Loop
End If

objRecordset.Close
objConnection.Close
MsgBox "Finish"

答案 1 :(得分:0)

A referral was returned from the server.通常表示您在连接到domainB时尝试在domainA中获取对象。

请尝试使用:

<LDAP://mainDC.com/OU=theOU,DC=mainDC,DC=com>

而不是:

<LDAP://OU=theOU,DC=mainDC,DC=com>

如果没有服务器,它将连接到当前计算机(或用户?)的域,该域可能不是mainDC.com。

要从林中的所有域搜索,您可以使用GC:

<GC://[GC server]>

但请注意,GC上只存在一部分属性。

答案 2 :(得分:0)

原来我要做的就是添加这个:

objCommand.Properties("Chase referrals") = ADS_CHASE_REFERRALS_ALWAYS

连接代码是:

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.Properties("Chase referrals") = ADS_CHASE_REFERRALS_ALWAYS

Set rootDSE = GetObject("LDAP://RootDSE")
Set dom = GetObject("LDAP://" & rootDSE.Get("defaultNamingContext"))
objCommand.CommandText = "<" & dom.ADsPath & ">;" & _
    "(&(objectClass=user)(objectCategory=Person)(sAMAccountName=" & LoginName & "));" & _
    "distinguishedName,sAMAccountName;subtree"
Set objRecordSet = objCommand.Execute

现在效果很好。

谢谢!