'returns all items thats starts with PC or Server on domain.local
Dim netpcs As ArrayList = GetDomainHosts("LDAP://dc=domain,dc=local", "PC*|Server*")
'returns all items on domain.local
Dim netpcs As ArrayList = GetDomainHosts("LDAP://dc=domain,dc=local")
Function GetDomainHosts(Optional ByVal LDAPDir As String = "LDAP://dc=domain,dc=local", Optional ByVal RegexHost As String = "") As ArrayList
Dim pc As New ArrayList
' 1. connect to your domain controller, binding using currently logged on credentials
Dim root As New DirectoryServices.DirectoryEntry(LDAPDir)
' 2. put together an ldap query to retrieve all computer accounts
Dim searcher As New DirectoryServices.DirectorySearcher(root)
searcher.Filter = "(objectClass=computer)"
searcher.SearchScope = DirectoryServices.SearchScope.Subtree
searcher.Sort = New DirectoryServices.SortOption("displayName", DirectoryServices.SortDirection.Descending)
' 3. execute the query
Dim results As DirectoryServices.SearchResultCollection = searcher.FindAll()
Dim pcname As String = ""
' 4. loop through the results
For Each computer As DirectoryServices.SearchResult In results
pcname = computer.GetDirectoryEntry().Properties("displayName").Value
If Not pcname = Nothing Then
pcname = pcname.Replace("$", "").ToLower
If RegexMatchingHost(pcname, RegexHost) Then
pc.Add(pcname)
End If
End If
Next
Return pc
End Function
Function RegexMatchingHost(ByVal Str As String, ByVal RegexMatchStr As String) As Boolean
Return System.Text.RegularExpressions.Regex.IsMatch( _
Str, _
RegexMatchStr, _
System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.Singleline)
End Function