Get a Complete Computer List From Active Directory Using .NET 2.0
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've used this code sample on several scripts and using Active Directory as the authoritative source for a list of machines is handy. The process running this code sample normally requires being 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'm connecting to. This represents an LDAP-based path to the Active Directory domain you are connecting to. You will want to change the code sample to what domain you are connecting to.
Try
Dim enTry As System.DirectoryServices.DirectoryEntry = _
New System.DirectoryServices.DirectoryEntry("LDAP://DC=Steve,DC=Schofield,DC=com")
Dim mySearcher As System.DirectoryServices.DirectorySearcher = _
New System.DirectoryServices.DirectorySearcher(enTry)
mySearcher.Filter = ("(objectClass=computer)")
Dim resEnt As System.DirectoryServices.SearchResult
For Each resEnt In mySearcher.FindAll()
Try
'The reason for using the MID statement is when retrieving computers
'With this method, they are formatted CN=COMPUTERNAME. The MID statement
'Parses out just the ComputerName. '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
Steve Schofield is a Senior Internet Support Specialist with ORCS Web, Inc. - a company that provides managed complex hosting for clients who develop and deploy their applications on Microsoft Windows platforms.