VB6 Get List of Active Directory Domains

2019-04-15 22:01发布

问题:

Using VB6, is it possible to get a list of all available domains in active directory?

Thanks, Alex

回答1:

Add references for ActiveDS type library, and ADO to your project.

Sub GetDomains()
   Dim objRootDSE As IADs
   Dim objBase As IADs
   Dim path As String
   Dim rsDomains As ADODB.Recordset
   Dim cnADS As ADODB.Connection
   Dim cmdCommand As ADODB.Command

   Set objRootDSE = GetObject("LDAP://rootDSE")
   path = "LDAP://" & objRootDSE.Get("rootDomainNamingContext")
   Set objBase = GetObject(path)

   Set cnADS = New ADODB.Connection
   cnADS.Provider = "ADsDSOObject"
   cnADS.Open "ADSI"

   Set cmdCommand = New ADODB.Command
   cmdCommand.ActiveConnection = cnADS
   cmdCommand.Properties("searchScope") = ADS_SCOPE_SUBTREE
   cmdCommand.CommandText = "SELECT Name, distinguishedName FROM '" & objBase.ADsPath & "' WHERE objectCategory = 'domain'"
   Set rsDomains = cmdCommand.Execute

   Do While rsDomains.EOF = False
      List1.AddItem (rsDomains!Name)
      rsDomains.MoveNext
   Loop

End Sub

I have only the one domain to test this against so I hope you'll need to let me know if it gets all the domains for you. Also please note, I didn't add error handling.