按 sAMAccountName VBA 查找用户

Find user by sAMAccountName VBA

我正在尝试通过 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.

此外,除了查询两次之外,是否有更简单的方法来搜索多个域?

谢谢!

找到这个片段,试一试。将第 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"

A referral was returned from the server. 通常意味着您在连接到域 B 时试图获取域 A 中的对象。

请尝试使用:

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

而不是:

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

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

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

<GC://[GC server]>

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

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

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

这现在工作正常。

谢谢!