Wednesday 9 March 2016

C# Querying Organisational Units in Active directory

I am working on active directory queries. I have decided to share come code I have found, coded and updated.

Reference :
AD: Active Directory
OU: OrganisationalUnit (used to structure your AD)

How to get Organisational units from AD using c# & LDAP.

NOTE The important information here is:
Each structure in active directory have its own name and many times I have come across of misspelling the types. For OU we have to setup filter to search only on:

objectCategory = organizationalUnit


Now the full code is as follows


// connect to "RootDSE" to find default naming context
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");

string defaultContext = rootDSE.Properties["defaultNamingContext"][0].ToString();

// bind to default naming context - if you *know* where you want to bind to - 
// you can just use that information right away
DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + defaultContext);

// set up directory searcher based on default naming context entry
DirectorySearcher ouSearcher = new DirectorySearcher(domainRoot);

// SearchScope: OneLevel = only immediate subordinates (top-level OUs); 
// subtree = all OU's in the whole domain (can take **LONG** time!)
ouSearcher.SearchScope = SearchScope.OneLevel;
// ouSearcher.SearchScope = SearchScope.Subtree;

// define properties to load - here I just get the "OU" attribute, the name of the OU
ouSearcher.PropertiesToLoad.Add("ou");

// define filter - only select organizational units
ouSearcher.Filter = "(objectCategory=organizationalUnit)";

// do search and iterate over results
foreach (SearchResult deResult in ouSearcher.FindAll())
{
    string ouName = deResult.Properties["ou"][0].ToString();
}
Links to Stack Overflow

http://stackoverflow.com/questions/16810382/getting-all-ous-from-a-active-directory

No comments:

Post a Comment