Click here to Skip to main content
6,295,667 members and growing! (13,340 online)
Email Password   helpLost your password?
Languages » C# » How To     Beginner License: The Code Project Open License (CPOL)

Retrieve Names from Nested AD Groups

By kian01

This code walks though all nested groups under an Active Directory group and returns all user names that are members of these.
C# (C# 2.0, C# 3.0), .NET (.NET 2.0, .NET 3.0, .NET 3.5), Visual Studio (VS2005), Dev
Posted:26 Jun 2008
Views:6,129
Bookmarked:13 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
3 votes for this article.
Popularity: 2.03 Rating: 4.25 out of 5

1

2
1 vote, 33.3%
3
1 vote, 33.3%
4
1 vote, 33.3%
5

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


Member

Occupation: Program Manager
Company: The Boston Consulting Group
Location: Germany Germany

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralGood Code - Thank You PinmemberSwizzleTits4:55 26 Jun '08  
GeneralRe: Good Code - Thank You Pinmemberkian0122:47 26 Jun '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Jun 2008
Editor: Deeksha Shenoy
Copyright 2008 by kian01
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project