Click here to Skip to main content
15,891,473 members
Articles / Programming Languages / C#
Article

Retrieve Names from Nested AD Groups

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
25 Jun 2008CPOL2 min read 59.8K   583   19   6
This code walks though all nested groups under an Active Directory group and returns all user names that are members of these.

Introduction

This is a very simple class that will search a given AD group and all groups beneath it and return all user accounts that are members of these groups.

This sounds really simple, and it is, but when I searched the Internet for a solution, I could not find one, so I thought I'd share it here.

Using the Code

There are basically three methods in this class, all are marked static, so you don't have to instantiate the class to use the public method.

Just call the method x(string strGroupName), pass in the name of the group (display name, not the DN), you get an ArrayList containing the SAM Account Names of all users in this group or any sub-group. If your AD should contain several groups with the same name, which is a bad practice anyway, it will just use the first it finds.

x will then call getUsersInGroup(string strGroupDN) passing in the DN of the group you chose.

getUsersInGroup will first collect all users that are members of this group, then walk though all groups in the given group and call itself recursively for each group.

In order to avoid endless loops when you have a circular group structure in AD, it keeps track of all "visited" groups in the global variable, searchedGroups.

I think the code is pretty much self-explanatory, so I just pasted it in below.

C#
using System;
using System.Collections;
using System.Text;

using System.DirectoryServices;

namespace ADgroupSearcher
{
    class getGroupMembers
    {
        /// <summary>
        /// searchedGroups will contain all groups already searched, in order to
        /// prevent endless loops when there are circular structures in the groups.
        /// </summary>
        static Hashtable searchedGroups = null;

        /// <summary>
        /// x will return all users in the group passed in as a parameter
        /// the names returned are the SAM Account Name of the users.
        /// The function will recursively search all nested groups.
        /// Remark: if there are multiple groups with the same name, 
        /// this function will just
        /// use the first one it finds.
        /// </summary>
        /// <param name="strGroupName">Name of the group, 
        /// which the users should be retrieved from</param>
        /// <returns>ArrayList containing the SAM Account Names 
        /// of all users in this group and any nested groups</returns>
        static public ArrayList x(string strGroupName)
        {
            ArrayList groupMembers = new ArrayList();
            searchedGroups = new Hashtable();

            // find group
            DirectorySearcher search = new DirectorySearcher("LDAP://DC=company,DC=com");
            search.Filter = String.Format
                            ("(&(objectCategory=group)(cn={0}))", strGroupName);
            search.PropertiesToLoad.Add("distinguishedName");
            SearchResult sru = null;
            DirectoryEntry group;

            try
            {
                sru = search.FindOne();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            group = sru.GetDirectoryEntry();

            groupMembers = getUsersInGroup
                          (group.Properties["distinguishedName"].Value.ToString());

            return groupMembers;
        }

        /// <summary>
        /// getUsersInGroup will return all users in the group passed in as a parameter
        /// the names returned are the SAM Account Name of the users.
        /// The function will recursively search all nested groups.
        /// </summary>
        /// <param name="strGroupDN">DN of the group, 
        /// which the users should be retrieved from</param>
        /// <returns>ArrayList containing the SAM Account Names 
        /// of all users in this group and any nested groups</returns>
        private static ArrayList getUsersInGroup(string strGroupDN)
        {
            ArrayList groupMembers = new ArrayList();
            searchedGroups.Add(strGroupDN, strGroupDN);

            // find all users in this group
            DirectorySearcher ds = new DirectorySearcher("LDAP://DC=company,DC=com");
            ds.Filter = String.Format
                        ("(&(memberOf={0})(objectClass=person))", strGroupDN);

            ds.PropertiesToLoad.Add("distinguishedName");
            ds.PropertiesToLoad.Add("givenname");
            ds.PropertiesToLoad.Add("samaccountname");
            ds.PropertiesToLoad.Add("sn");

            foreach (SearchResult sr in ds.FindAll())
            {
                groupMembers.Add(sr.Properties["samaccountname"][0].ToString());
            }

            // get nested groups
            ArrayList al = getNestedGroups(strGroupDN);
            foreach (object g in al)
            {
                // only if we haven't searched this group before - avoid endless loops
                if (!searchedGroups.ContainsKey(g)) 
                {
                    // get members in nested group
                    ArrayList ml = getUsersInGroup(g as string);
                    // add them to result list
                    foreach (object s in ml)
                    {
                        groupMembers.Add(s as string);
                    }
                }
            }

            return groupMembers;
        }

        /// <summary>
        /// getNestedGroups will return an array with the DNs of all groups contained
        /// in the group that was passed in as a parameter
        /// </summary>
        /// <param name="strGroupDN">DN of the group, 
        /// which the nested groups should be retrieved from</param>
        /// <returns>ArrayList containing the DNs of each group 
        /// contained in the group passed in as a parameter</returns>
        private static ArrayList getNestedGroups(string strGroupDN)
        {
            ArrayList groupMembers = new ArrayList();

            // find all nested groups in this group
            DirectorySearcher ds = new DirectorySearcher("LDAP://DC=company,DC=com");
            ds.Filter = String.Format
                        ("(&(memberOf={0})(objectClass=group))", strGroupDN);

            ds.PropertiesToLoad.Add("distinguishedName");

            foreach (SearchResult sr in ds.FindAll())
            {
                groupMembers.Add(sr.Properties["distinguishedName"][0].ToString());
            }

            return groupMembers;
        }
    }
}

Final Remarks

This code is provided for your convenience. It certainly needs proper error handling added, and maybe there are better solutions? I will not change the code, as it does what I needed it to do. I used it for a one-time chore only. If you know better/faster solutions, I look forward to your comments.

History

  • 26th June, 2008: Initial post

License

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



Comments and Discussions

 
QuestionUsing principal context Pin
Member 1393258931-Jul-18 3:07
Member 1393258931-Jul-18 3:07 
SuggestionHow to get more detailed information using the same code. Pin
sushantkk26-Jul-18 1:06
sushantkk26-Jul-18 1:06 
SuggestionSimpler version of code Pin
BowmarBrain10-May-13 11:11
BowmarBrain10-May-13 11:11 
GeneralGeneral comments Pin
pdxguy10-Jul-09 7:51
pdxguy10-Jul-09 7:51 
GeneralGood Code - Thank You Pin
SwizzleTits26-Jun-08 3:55
SwizzleTits26-Jun-08 3:55 
GeneralRe: Good Code - Thank You Pin
User 143113526-Jun-08 21:47
User 143113526-Jun-08 21:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.