Click here to Skip to main content
Click here to Skip to main content

Retrieve Names from Nested AD Groups

, 26 Jun 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

using System;
using System.Collections;
using System.Text;

using System.DirectoryServices;

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

        /// <span class="code-SummaryComment"><summary></span>
        /// 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.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="strGroupName">Name of the group, </span>
        /// which the users should be retrieved from<span class="code-SummaryComment"></param></span>
        /// <span class="code-SummaryComment"><returns>ArrayList containing the SAM Account Names </span>
        /// of all users in this group and any nested groups<span class="code-SummaryComment"></returns></span>
        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;
        }

        /// <span class="code-SummaryComment"><summary></span>
        /// 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.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="strGroupDN">DN of the group, </span>
        /// which the users should be retrieved from<span class="code-SummaryComment"></param></span>
        /// <span class="code-SummaryComment"><returns>ArrayList containing the SAM Account Names </span>
        /// of all users in this group and any nested groups<span class="code-SummaryComment"></returns></span>
        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;
        }

        /// <span class="code-SummaryComment"><summary></span>
        /// getNestedGroups will return an array with the DNs of all groups contained
        /// in the group that was passed in as a parameter
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="strGroupDN">DN of the group, </span>
        /// which the nested groups should be retrieved from<span class="code-SummaryComment"></param></span>
        /// <span class="code-SummaryComment"><returns>ArrayList containing the DNs of each group </span>
        /// contained in the group passed in as a parameter<span class="code-SummaryComment"></returns></span>
        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)

Share

About the Author

kian01
Program Manager The Boston Consulting Group
Germany Germany
No Biography provided

Comments and Discussions

 
SuggestionSimpler version of code [modified] PinmemberBowmarBrain10-May-13 12:11 
GeneralGeneral comments Pinmemberpdxguy10-Jul-09 8:51 
GeneralGood Code - Thank You PinmemberSwizzleTits26-Jun-08 4:55 
GeneralRe: Good Code - Thank You Pinmemberkian0126-Jun-08 22:47 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 26 Jun 2008
Article Copyright 2008 by kian01
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid