views:

65

answers:

1

I'm trying to get a list of the groups that are in an AD group using .NET.

As an example, I have a group called TestGroup and inside that group I have the group DomainAdministrators.

Using the code below I can get all of the users including those from the DomainAdministrators group but not the group itself.

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DomainName");
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "TestGroup");

ArrayList members = new ArrayList();

if (grp != null)
{
    foreach (Principal p in grp.GetMembers(true))
    {
        members.Add(p.Name)
    }

}   
grp.Dispose();
ctx.Dispose();

Instead of GetMembers I've tried GetGroups but that doesn't return anything. How can I return the groups in the group?

A: 

Seems if you don't execute GetMembers recursively (pass in false) you get users and groups and just need to filter by StructuralObjectClass.

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DomainName"); 
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "TestGroup"); 

ArrayList users = new ArrayList();
ArrayList groups = new ArrayList(); 

if (grp != null) 
{ 
    foreach (Principal p in grp.GetMembers(false)) //set to false
    {
        if (p.StructuralObjectClass == "user")
            users.Add(p.Name);
        else if (p.StructuralObjectClass == "group")
            groups.Add(p.Name);
    }
}    
grp.Dispose(); 
ctx.Dispose();
Douglas Anderson