List of users in specific Active Directory Distribution Group

前端 未结 2 1780
遇见更好的自我
遇见更好的自我 2021-01-05 08:45

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

2条回答
  •  一生所求
    2021-01-05 09:24

    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 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
     }
    

提交回复
热议问题