Parse the Active Directory group recursively and print all the members

This program will parse the specified group recursively and will prints all the users available in all nested group.

You can directly use this program. Build an run by providing the group name as an argument like below:

C:\ ADGroupSearcher.exe mygroup => List of members of nested groups

Complete C# Program
-----------------------

using System;
using System.Collections;
using System.Windows.Forms;

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 structured in the groups.
        /// </summary>
        static Hashtable searchedGroups = null;


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] argv)
        {
            Console.WriteLine("Searching");
            try
            {
                ArrayList nested_group_members = GetNestedGroupsUsers(argv[0]);
                foreach (string str in nested_group_members)
                {
                    Console.WriteLine(str);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception : " + ex.Message);
            }
            Console.WriteLine("Press any key to exit..");
            Console.Read();
        }
        /// <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 GetNestedGroupsUsers(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("samaccountname");

            try
            {
                foreach (SearchResult sr in ds.FindAll())
                {
                    Console.WriteLine(sr.Properties["samaccountname"][0].ToString());
                }
            }
            catch {
                //ignore if any properties found in AD
            }

            // get nested groups
            ArrayList al = getNestedGroups(strGroupDN);
            foreach (object g in al)
            {
                if (!searchedGroups.ContainsKey(g)) // only if we haven't searched this group before - avoid endless loops
                {
                    // get members in nested group
                    ArrayList ml = getUsersInGroup(g as string);
                    // add them to result list
                    foreach (object s in ml)
                    {
                        Console.WriteLine(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 apssed in asa 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;
        }
    }
}

Regards,
Megha

By Perry    Popularity  (5454 Views)