I am writing my first code to read all the members of an AD group and am not getting the correct number of group members:
public static void GetListOfAdUsersByGroup (string domainName, string groupName) {
PrincipalContext ctx = new PrincipalContext (ContextType.Domain); // Set up the domain context
GroupPrincipal group = GroupPrincipal.FindByIdentity (ctx, groupName); // Find the specified group
if (group != null) {
foreach (Principal p in group.GetMembers()) {
Console.WriteLine ("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
}
}
}
Already I have a problem. group.Members.Count is 3 and I print those 3 members, but the number should be much larger. What could I be doing wrong so early?
EDIT: I am getting two errors in the Output window right before my 3 users are listed. The errors are:
Exception thrown: 'System.ArgumentException' in mscorlib.dll Exception thrown: 'System.FormatException' in mscorlib.dll
EDIT 2:
I basically stole the following code from somewhere else, and am also getting 3 results from this code as well!
public static IEnumerable<string> GetGroupMemberList (GroupPrincipal group, bool recursive = false) {
using (var memberPrincipals = group.GetMembers(recursive)) {
foreach (Principal member in memberPrincipals) {
yield return member.SamAccountName;
}
}
}
Calling like this:
PrincipalContext ctx = new PrincipalContext (ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity (ctx, "DOC.WKCC");
_elements = new List<string>(GetGroupMemberList (group, true));