Click here to Skip to main content
Licence CPOL
First Posted 26 Jun 2008
Views 13,659
Downloads 84
Bookmarked 17 times

Retrieve Names from Nested AD Groups

By kian01 | 26 Jun 2008
This code walks though all nested groups under an Active Directory group and returns all user names that are members of these.

1

2
1 vote, 25.0%
3
1 vote, 25.0%
4
2 votes, 50.0%
5
4.50/5 - 4 votes
μ 4.50, σa 1.68 [?]

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
    {
        /// <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)

About the Author

kian01

Program Manager
The Boston Consulting Group
Germany Germany

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGeneral comments Pinmemberpdxguy8:51 10 Jul '09  
Just a couple of comments:
 
(1) Many of the System.DirectoryServices classes implement IDisposable, for good reason - the ASDI resources. One may wish to employ a 'using' block in 2.0 or higher, or declare them set to null and add a finally{} block to dispose if not null.
 
System.DirectoryServices.DirectorySearcher mySearcher = null;
.
. (do something) in a try{} block
.
finally
{
if (mySearcher != null)
{
mySearcher.Dispose();
mySearcher = null;
}
}
 
(2) If you are in a large organization, this code may not return all members because of limits on the # of records AD returns. AD will return a SearchResult property "member;range=n-*" if you are at the end, but otherwise you need to increment the range and keep calling AD until all are retrieved. Check the web -- lots of examples on this out there.
 
(3) Might want to add a recursion for multiple nesting levels.
GeneralGood Code - Thank You PinmemberSwizzleTits4:55 26 Jun '08  
GeneralRe: Good Code - Thank You Pinmemberkian0122:47 26 Jun '08  

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.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120210.1 | Last Updated 26 Jun 2008
Article Copyright 2008 by kian01
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid