How to get a list of groups in an Active Directory group

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

As an example, I have a group called TestGroup and within this group I have a DomainAdministrators group.

Using the code below, I can get all 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 it doesn't return anything. How do I return groups to a group?

+2


source to share


1 answer


It seems that if you don't do GetMembers recursively (go to false) you get users and groups and you just need to filter the 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();

      

+4


source







All Articles