Enumerate members of an Active Directory group in .Net

My previous post [Click Link] shows how to enumerate members of an AD group using an LDAP query written in VBscript.

Here I am showing you how to do the same using C#. Although, this function is not recursive (i.e doesn’t list members of a group that may be nested within the group you have specified)

            DirectoryEntry group = new DirectoryEntry(LDAP://CN=GroupXXX,OU=Groups,
OU=Company,DC=ww,DC=xx,DC=yy,DC=zz);
            object members = group.Invoke("Members", null);
            String s = "";

            foreach (object member in (IEnumerable)members)
            {
                DirectoryEntry x = new DirectoryEntry(member);
                s+= x.Properties["displayName"].Value + "\n";
            }
 
            MessageBox.Show( s);

I know, after reading this you are thinking, “I hate these code examples where they conveniently show you a long LDAP string, and tell you to figure out the DN of the group yourself”.  To figure out what you need to put in the long LDAP:// string..you can use this piece of vbscript code.

  
        Group = "GroupXXX"
        rs = CreateObject("ADODB.RecordSet")
        rs.Open(";(sAMAccountName=" & Group & ");adspath", "provider=ADsDSOObject") 

        If Not rs.EOF Then
            s = rs(0).Value
        End If 

        MsgBox(s)

NOTE: If you are so LDAP /Active Directory challenged that you cannot figure out what to put in the ww, xx, yy, zz. Then you can go to Start–>Adminstrative Tools–>Active Directory Users and Computer and you will see your domain name in the format ww.xx.yy.zz……..


2 Responses

  1. Hello,

    I found this blog, that enumerate the members for a group of Active Directory, but only lists the users that this group isn’t the primary group. (if one user has the group as a primary group, doesn’t shown this users)

    Example

    In the group D01, I have three users (U01, U02, U03) and the primary group of U02 is D01. when you use the method “members” for enumerating the members of the group, doesn’t list the User U02. Only list U01 and U03

    thank you

    • Sorry, there is nothing that comes to me. This is the first time I have heard a problem like this. Also, as you know AD is very difficult to troubleshoot, without having a similar setup here, I couldnt help you out with it.

      However, if you find a solution, it will be great to share it with the rest of the community by either emailing me or adding to your own comment.

      -Nishant

Leave a Reply