locked
Getting Group Memberships With DirectoryServices RRS feed

  • Question

  • User2106497420 posted

    I'm still fairly new to .NET, and am hoping someone can shed some light on a weird issue I'm having. I'm trying to write a method that can accept the name of an Active Directory computer, user, or group, and spit back the nested/recursive list of group memberships that object belongs to.

    Right now I've got it giving me 121 entries, when it should be giving me 135. I can't figure out why I'm not getting everything.

    Can someone tell me if there's something wrong with my code?

    Thanks!

            public List<string> EnumerateAllGroupMemberships(string objectName)
            {
                List<string> groupsList = new List<string>();
                using (DirectoryEntry directoryEntry = CreateDirectoryEntry(myDomainRoot))
                {
                    using (DirectorySearcher directorySearcher = new DirectorySearcher())
                    {
                        directorySearcher.SearchRoot = directoryEntry;
                        directorySearcher.PropertiesToLoad.Add("memberOf");
                        GetGroupMembershipsRecursively(directorySearcher, objectName, groupsList);
                    }
                }
                groupsList.Sort();
                return groupsList;
            }
    
            private void GetGroupMembershipsRecursively(DirectorySearcher directorySearcher, string objectName, List<string> groupsList)
            {
                directorySearcher.Filter = "(name=" + objectName + ")";
                SearchResult result = directorySearcher.FindOne();
                if (result != null)
                {
                    var memberOfCollection = result.Properties["memberOf"];
                    foreach (var entry in memberOfCollection)
                    {
                        string groupDN = entry.ToString();
                        if (!groupsList.Contains(groupDN)) //Skip groups that have already been found
                        {
                            groupsList.Add(groupDN);
                            string groupName = GetNameFromDN(groupDN);
                            GetGroupMembershipsRecursively(directorySearcher, groupName, groupsList);
                        }
                    }
                }
            }
    
    Friday, December 8, 2017 10:42 PM

Answers

  • User2106497420 posted

    It never seems to fail... Post on a forum, spend five more minutes looking at the code and go "ah-ha!". Turned out I had to switch from "name" in my filter to "distinguishedName", and then the counts looked better. Now I can clean up the methods a little more...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 8, 2017 11:03 PM