I want to recover a complete list of computers and the domains that they are in from Active Directory using the functionailty built in to .NET 2.0. I have determined how to get ALL computers in the default domain using the following code:
// Identify the 'default' AD/LDAP Server
DirectoryEntry defaultServer = new DirectoryEntry("LDAP://roo
tDSE");
string strLdapServer = (string)defaultServer.Prop
erties["de
faultNamin
gContext"]
.Value;
DirectoryEntry mySearchRoot = new DirectoryEntry("LDAP://" + strLdapServer);
// Create a 'DirectoryEntry' object to search.
DirectorySearcher myDirectorySearcher = new DirectorySearcher(mySearch
Root);
myDirectorySearcher.Filter
= ("(objectClass=computer)")
;
// Iterate through (any) results
foreach(SearchResult resEnt in myDirectorySearcher.FindAl
l())
{
// Get the 'DirectoryEntry' that corresponds to 'mySearchResult'.
DirectoryEntry myDirectoryEntry = resEnt.GetDirectoryEntry()
;
string strComputer = myDirectoryEntry.Name.ToSt
ring();
}
...and I have also determined code to recover a list of domains defined within AD as :
List<string> domains = new List<string>()
DirectoryEntry en = new DirectoryEntry("LDAP://");
// Search for objectCategory type "Domain"
DirectorySearcher srch = new DirectorySearcher("objectC
ategory=Do
main");
SearchResultCollection coll = srch.FindAll();
// Enumerate over each returned domain.
foreach (SearchResult rs in coll)
{
ResultPropertyCollection resultPropColl = rs.Properties;
foreach (object domainName in resultPropColl["name"])
{
domains.Add(domainName.ToS
tring());
}
}
...now what I want to do is to use the name of the domain returned as above to recover the name of any computers within this domain. I did try using the following code:
string ldapString = "LDAP://" + domainName + "/CN=Computers,DC=" + domainName + ",DC=com";
DirectoryEntry domain = new DirectoryEntry(ldapString)
;
foreach (DirectoryEntry child in domain.Children)
{
string computerName = child.Name;
if (computerName != "")
computers.Add(new string[] { computerName, domainName });
}
But this fails to connect to the AD server. Ultimately I need some code which, given the domain name, is able to query the AD server for that domain and recover the list of computers on that domain but I seem to be having problems determining the correct LDAP string.
Start Free Trial