2012-08-29 59 views
1

所有域我有搜索一個特定的用戶和輸出的全名,電子郵件和部門從Active Directory以下VBA代碼:VBA:LDAP搜索通過森林

Public Type LDAPUserInfo 
    FullName As String 
    Email As String 
    Department As String 
    AccountStatus As String 
End Type 


Function FindUser(ByVal username) As LDAPUserInfo 
On Error GoTo Err 

Dim objRoot As Variant 
Dim LDAPdomainName As String 
Dim cn As Variant 
Dim cmd As Variant 
Dim rs As Variant 
Dim LDAPUserInfo As LDAPUserInfo 

Set cn = CreateObject("ADODB.Connection") 
Set cmd = CreateObject("ADODB.Command") 
Set rs = CreateObject("ADODB.Recordset") 

Set objRoot = GetObject("LDAP://RootDSE") 
LDAPdomainName = objRoot.Get("defaultNamingContext") 'Contains the distinguished name for the domain of which this directory server is a member. 
'http://msdn.microsoft.com/en-us/library/windows/desktop/ms684291(v=vs.85).aspx 

cn.Open "Provider=ADsDSOObject;" 

cmd.activeconnection = cn 
'cmd.commandtext = "SELECT ADsPath FROM 'LDAP://" & Domain & "' WHERE sAMAccountName = '" & UserName & "'" 
'To see all attributes names available, connect with Active Directory Explorer and add to Select. 
cmd.commandtext = "SELECT cn, mail, physicalDeliveryOfficeName, userAccountControl FROM 'LDAP://" & LDAPdomainName & "' WHERE sAMAccountName = '" & username & "'" 
Set rs = cmd.Execute 

    Debug.Print rs("cn") & " E-mail: " & rs("mail") & " Dept: " & rs("physicalDeliveryOfficeName") 
    LDAPUserInfo.FullName = Nz(rs("cn"), "") 
    LDAPUserInfo.Email = Nz(rs("mail"), "") 
    LDAPUserInfo.Department = Nz(rs("physicalDeliveryOfficeName"), "") 

    FindUser = LDAPUserInfo 


If Not rs Is Nothing Then rs.Close 
If Not cn Is Nothing Then cn.Close 

Exit_Err: 

Set rs = Nothing 
Set cmd = Nothing 
Set cn = Nothing 
Set objRoot = Nothing 
Exit Function 

Err: 

If Err <> 0 Then 
    MsgBox "Error connecting to Active Directory Database: " & Err.Description & vbCrLf & _ 
      "User: " & username, , "Error: " & Err.Number 
Else 
    If Not rs.BOF And Not rs.EOF Then 
     rs.MoveFirst 
     MsgBox rs(0) 
    Else 
     MsgBox "Not Found" 
    End If 
End If 
Resume Exit_Err 

End Function 

它與用戶是在主要領域。有沒有辦法改變LDAPdomainName,以便它可以搜索所有子域?

回答

1

根據您的特定森林配置,答案會有所不同。

一般來說,如果您也想搜索子域名,您可以要求ADSI做所謂的追蹤推薦。如果你搜索ADSI +追蹤推薦,你會得到大量的點擊......並且根據你最終使用的API,每個API都有一個答案。 一些這方面的信息在這裏:http://technet.microsoft.com/en-us/library/cc978014.aspx

這就是說,有一些細微差別:

  • 如果您有多個域那裏沒有從命名空間角度林中所有域的單親(前:假設有一個森林與foo.com,bar.foo.com和blech.com ......沒有一個單獨的父母涵蓋他們),那麼你要麼做多次搜索或使用所謂的幻影根控制(在那裏你可以通過不存在的最高父母,指示AD去搜索每個人)
  • 請記住,這個搜索將在你的前面碰到DC st ...爲每個你追逐的領域提供一個。如果您只搜索有限的一組屬性,則可能需要使用全局編錄服務器,它可以爲來自該服務器的所有域(即更快的搜索,因爲它全部是本地的)提供服務信息。要做到這一點,你需要連接到全局編錄端口,通常是3268/3269(後者是LDAPS)。