Get Groups From OU using DirectoryServices.AccountManagement

teebot picture teebot · Dec 18, 2009 · Viewed 28k times · Source

I'd like to use AccountManagement to list all the groups in an Organizational Unit.

The following snippet works with DirectoryServices but I would have to instanciate GroupPrincipal with the DirectoryEntry path in the result (which feels like a dirty fix).

DirectoryEntry root = new DirectoryEntry("LDAP://OU=Marketing,OU=Operations,OU=Applications,DC=mycompany,DC=local")
        DirectorySearcher ds = new DirectorySearcher(root);
        ds.Filter = "(objectCategory=group)";
        SearchResultCollection results = ds.FindAll();

Has anyone an idea?

Thanks!

Answer

Per Noalt picture Per Noalt · Dec 18, 2009

You can set the PrincipalContext to the OU where you want to start the search and use the PrincipalSearcher-class in System.DirectoryService.AccountManagement to accomplish what you need, like this:

PrincipalContext yourOU = new PrincipalContext(ContextType.Domain, "mycompany.local", "OU=Marketing,OU=Operations,OU=Applications,DC=mycompany,DC=local");
GroupPrincipal findAllGroups = new GroupPrincipal(yourOU, "*");
PrincipalSearcher ps = new PrincipalSearcher(findAllGroups);
foreach(var group in ps.FindAll())
{
  Console.WriteLine(group.DistinguishedName);
}
Console.ReadLine();