In a web app, we\'re looking to display a list of sam accounts for users that are a member of a certain group. Groups could have 500 or more members in many cases and we need t
Here is a recursive search (search users in nested groups) using ADSI.
static void Main(string[] args)
{
/* Connection to Active Directory
*/
string sFromWhere = "LDAP://SRVENTR2:389/dc=societe,dc=fr";
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "societe\\administrateur", "test.2011");
/* To find all the users member of groups "Grp1" :
* Set the base to the groups container DN; for example root DN (dc=societe,dc=fr)
* Set the scope to subtree
* Use the following filter :
* (member:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=X)
*/
DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
dsLookFor.Filter = "(&(memberof:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=societe,DC=fr)(objectCategory=user))";
dsLookFor.SearchScope = SearchScope.Subtree;
dsLookFor.PropertiesToLoad.Add("cn");
dsLookFor.PropertiesToLoad.Add("samAccountName");
SearchResultCollection srcUsers = dsLookFor.FindAll();
/* Just show each user
*/
foreach (SearchResult srcUser in srcUsers)
{
Console.WriteLine("{0}", srcUser.Path);
Console.WriteLine("{0}", srcUser.Properties["samAccountName"][0]);
}
Console.ReadLine();
}
For @Gabriel Luci comment : Microsoft documentation
memberOf
The memberOf attribute is a multi-valued attribute that contains groups of which the user is a direct member, except for the primary group, which is represented by the primaryGroupId. Group membership is dependent on the domain controller (DC) from which this attribute is retrieved:
At a DC for the domain that contains the user, memberOf for the user is complete with respect to membership for groups in that domain; however, memberOf does not contain the user's membership in domain local and global groups in other domains.
At a GC server, memberOf for the user is complete with respect to all universal group memberships. If both conditions are true for the DC, both sets of data are contained in memberOf.
Be aware that this attribute lists the groups that contain the user in their member attribute—it does not contain the recursive list of nested predecessors. For example, if user O is a member of group C and group B and group B were nested in group A, the memberOf attribute of user O would list group C and group B, but not group A.
This attribute is not stored—it is a computed back-link attribute.