Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

Anyone here know how to get the list of "distinguished name" of security groups in an Organisation Unit (OU) from Active directory using c# code?

I have used the below code which will give only the list of "distinguished name" of all the OUs from active directory. But what I want is to get the list of "distinguished name" of all the SECURITY GROUP INSIDE THAT OU.

What I have tried:

C#
public static List<string> ListOu()
    {
        List<string> ous = new List<string>();
        using (DirectoryEntry root = new DirectoryEntry("LDAP://dc=DOMAIN,dc=COM"))
        {
            DirectorySearcher searcher = new DirectorySearcher(root);
            searcher.Filter = "(&(objectClass=organizationalUnit))";
            searcher.SearchScope = SearchScope.Subtree;
            searcher.PropertiesToLoad.Add("distinguishedName");

            var result = searcher.FindAll();
            foreach (SearchResult entry in result)
            {
                ous.Add(entry.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString());
            }        

            result.Dispose();
            searcher.Dispose();
        }
        return ous;
    }
Posted
Updated 6-Feb-18 13:50pm
v2

1 solution

The distinguished name for a Security Group includes the Organisational Unit, therefore instead of getting the Units in the first place, just query for all Groups

C#
public static List<string> ListOu()
    {
        List<string> ous = new List<string>();
        using (DirectoryEntry root = new DirectoryEntry("LDAP://dc=DOMAIN,dc=COM"))
        {
            DirectorySearcher searcher = new DirectorySearcher(root);
            // Get all Groups
            searcher.Filter = "(&(objectClass=group))";
            searcher.SearchScope = SearchScope.Subtree;
            searcher.PropertiesToLoad.Add("distinguishedName");

            SearchResultCollection result = searcher.FindAll();
            foreach (SearchResult entry in result)
            {
        ous.Add(entry.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString());                           
            }        

            result.Dispose();
            searcher.Dispose();
        }
        return ous;
    }


Kind Regards
 
Share this answer
 
Comments
Adarsh A Nair 6-Feb-18 21:00pm    
Thank you so much bro. It works, I got the expected result. Thank you again. :)
an0ther1 6-Feb-18 21:20pm    
Thanks Adarsh, my pleasure
Animesh Datta 7-Feb-18 0:05am    
My 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900