This code sample shows how to retrieve a list of computers
from Active Directory and use a For/Next to loop through the collection.
I have used this code sample on several scripts. Using Active Directory as the
authoritative source for a list of machines is very handy. The process
running this code sample normally requires a domain administrator level to
retrieve this information.
Note: The "LDAP://DC=Steve,DC=Schofield,DC=com"
is the LDAP path for the domain I am connecting to. This represents an
LDAP-based path to the Active Directory domain you are connecting to. You
will have to change the code sample to what domain you are connecting to.
Code Listing 1:
Try
Dim enTry As System.DirectoryServices.DirectoryEntry = _
New System.DirectoryServices.DirectoryEntry("LDAP://DC=Steve,DC=Schofield,DC=com")
Dim mySearcherAs System.DirectoryServices.DirectorySearcher = _
New System.DirectoryServices.DirectorySearcher(enTry)
mySearcher.Filter = ("(objectClass=computer)")
Dim resEntAs System.DirectoryServices.SearchResult
For Each resEnt In mySearcher.FindAll()
Try
'The reason for using the MID statement is when retrievingcomputers
'with this method, they are formated CN=COMPUTERNAME. TheMID statement
'parses out just theComputerName. 'CN' stands for 'common name', this is
'the way LDAP stores the computer variable.
Console.WriteLine(":Processing:" &Mid(resEnt.GetDirectoryEntry().Name.ToString(), 4))
Catch ex As Exception
Console.WriteLine("Trying to Connect to: " & _
resEnt.GetDirectoryEntry().Name.ToString() & vbCrLf &ex.Message.ToString())
End Try
Next
Catch
End Try