0

How can I get a list of every user and/or Group that is located inside of an LDAP organization unit?

I am trying to query my LDAP server using c#. I want to get a list of all my distribution lists. All of my distribution lists are grouped under an organization-unit (OU) called "General Distributions." How can I get a list of all members under the "General Distributions" OU?

Below is the code I am using to query the LDAP service which is returning no results.

try
{
        DirectoryEntry objADAM = new DirectoryEntry("LDAP://my_domain.com", "user@my_domain.com", "password");

        DirectorySearcher objSearchADAM = new DirectorySearcher(objADAM);
        objSearchADAM.Filter = "(&(OU=General Distributions,DC=my_domain,DC=com)"; 
        objSearchADAM.SearchScope = SearchScope.Subtree;
        SearchResultCollection objSearchResults = objSearchADAM.FindAll();


        // Binding path. 
        List<string> result = new List<string>();

        if (objSearchResults.Count != 0)
        {
            foreach (SearchResult objResult in objSearchResults)
            {
                DirectoryEntry objGroupEntry = objResult.GetDirectoryEntry();
                result.Add(objGroupEntry.Name);
            }

            return result;
        }

        throw new Exception("No result found");
}
catch (Exception e)
{
        throw e;
}
Junior
  • 11,602
  • 27
  • 106
  • 212
  • what happens if you change your filter to something more like: `objSearchADAM.Filter = $"(&(memberOf=General Distribution)(objectClass=user))"` and add the scope to your `DirectoryEntry`: `LDAP://my_domain.com/OU=[higherLevelOu];Distributions,DC=my_domain,DC=com` – Jonathan Jul 09 '18 at 23:33
  • There is no higher OU. Not sure what to put but using the `(&(memberOf=General Distribution)(objectClass=user))` did not work – Junior Jul 10 '18 at 00:27

1 Answers1

1

I know this question is a bit old, but the answer is fairly simple. Use the OU itself as the DirectoryEntry you're using as the SearchRoot:

DirectoryEntry objADAM = new DirectoryEntry(
    "LDAP://my_domain.com/OU=General Distributions,DC=my_domain,DC=com",
    "user@my_domain.com", "password");

DirectorySearcher objSearchADAM = new DirectorySearcher(objADAM);
objSearchADAM.Filter = "(|(objectClass=user)(objectClass=group))"; //only get users and groups
objSearchADAM.SearchScope = SearchScope.Subtree;
SearchResultCollection objSearchResults = objSearchADAM.FindAll();
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • Sounds obvious once you read your answer. In Ruby the equivalent is the `treebase` parameter of the `Net::LDAP.new.search` method – Sumak Aug 25 '21 at 07:26