I\'m trying to get a list of users and some properties about the user from within an active directory group.
Update:
Here are the two method
Scope your search wider, wherever the members may be:
Dim directoryEntry As New DirectoryEntry("LDAP://OU=All,DC=Domain,DC=com")
Filter based on group membership:
directorySearcher.Filter = "(&(objectCategory=person)" & _
"(objectClass=user)" & _
"(memberOf=CN=MyGroup,OU=Groups,OU=All,DC=Domain,DC=com))"
IF you can, do upgrade to .NET 3.5 and use the new much improved System.DirectoryServices.AccountManagement
namespace. Great intro for those new classes is found in Managing Directory Security Principals in the .NET Framework 3.5.
With this, your job becomes trivial:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "MyGroup");
PrincipalSearchResult<Principal> members = group.GetMembers();
Does that work for you?
If you cannot use .NET 3.5, you should inspect the member
property of the group. The group members are not stored as children logically underneath the group in hierarchy, so you cannot find them by using a DirectorySearcher
.
DirectoryEntry group = new DirectoryEntry("LDAP://CN=MyGroup,OU=Groups,OU=All,DC=Domain,DC=com");
foreach(object groupMemberDN in group.Properties["member"])
{
// grab the group member's DN
}
See the Quick List of C# Code Examples for Active Directory (or the same for Visual Basic .NET) in the MSDN library for this snippet and more.
Update: if you need the users belonging to a particular group (since you want to update their properties or something), you could reverse the approach: search for all the users who have a memberOf
property equivalent to the group's DN:
DirectoryEntry root = new DirectoryEntry("LDAP://dc=domain,dc=com");
DirectorySearcher searcher = new DirectorySearcher(root);
searcher.Filter = "(&(objectCategory=user)(memberOf=CN=MyGroup,OU=Groups,OU=All,DC=Domain,DC=com))";
// set other properties on the searcher
foreach(object result in searcher.FindAll())
{
// do whatever you need to do with the entry
}