Skip to content

Get computers and domains in Active Directory

November 18, 2014

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://rootDSE”);
string strLdapServer = (string)defaultServer.Properties[“defaultNamingContext”].Value;
DirectoryEntry mySearchRoot = new DirectoryEntry(“LDAP://” + strLdapServer);

// Create a ‘DirectoryEntry’ object to search.
DirectorySearcher myDirectorySearcher = new DirectorySearcher(mySearchRoot);
myDirectorySearcher.Filter = (“(objectClass=computer)”);

// Iterate through (any) results
foreach(SearchResult resEnt in myDirectorySearcher.FindAll())
{
// Get the ‘DirectoryEntry’ that corresponds to ‘mySearchResult’.
DirectoryEntry myDirectoryEntry = resEnt.GetDirectoryEntry();
string strComputer = myDirectoryEntry.Name.ToString();
}

…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(“objectCategory=Domain”);
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.ToString());
}
}

…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.

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: