从Active Directory中获取一个组内的所有用户

29
我试图获取AD中特定组的所有用户,然后将其作为映射到我的Employee类中的属性的员工列表返回。我的过滤器没有产生结果 - 应该是什么?我还尝试了这里的第一种解决方案:特定活动目录分发组中的用户列表,但我需要诸如移动电话、分机等详细信息,而这种方法无法获取。
public static List<Employee> CreateEmployeeList(string department)
{
    List<Employee> employees = new List<Employee>();
    string filter = string.Format("(&(ObjectClass=person)(memberOf=CN={0},OU=Users & Groups,OU=Blah,DC=Blah,DC=Blah,DC=Blah))", department);

    DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
    DirectorySearcher searcher = new DirectorySearcher(adRoot);
    searcher.SearchScope = SearchScope.Subtree;
    searcher.ReferralChasing = ReferralChasingOption.All;
    searcher.Filter = filter;
    SearchResultCollection results = searcher.FindAll();

    foreach (SearchResult user in results)
    {
        // do whatever you need to do with the entry

        if (user != null)
        {
            UserDirectoryEntry = user.GetDirectoryEntry();
            string displayName = GetUserProperty("displayName");
            string firstName = GetUserProperty("givenName");
            string lastName = GetUserProperty("sn");
            string email = GetUserProperty("mail");
            string tel = GetUserProperty("telephonenumber");
            string extension = GetUserProperty("ipphone");
            string mobile = GetUserProperty("mobile");
            string title = GetUserProperty("description");
            employees.Add(new Employee{ FullName = displayName, FirstName = firstName, Surname = lastName, Email = email.ToLower(), Telephone = tel, Extension = extension, Mobile = mobile, JobTitle = title });
        }
    }
    return employees;
}
5个回答

65
using (var context = new PrincipalContext(ContextType.Domain, "domainName"))
{
    using (var group = GroupPrincipal.FindByIdentity(context, "groupName"))
    {
        if (group == null)
        {
            MessageBox.Show("Group does not exist");
        }
        else
        {
            var users = group.GetMembers(true);
            foreach (UserPrincipal user in users)
            {
                 //user variable has the details about the user 
            }
        } 
    }
}

1
完美的解决方案,谢谢!顺便说一句,在.NET Framework 4.5中不需要将“domainName”放入其中。 - Tom
8
需要引用 System.DirectoryServices.AccountManagement。 - Rok Strniša
1
不幸的是,这只返回用户对象作为组成员,而不返回联系人对象作为组成员。有没有办法返回所有组成员? - BardMorgan
2
此外,成员可以是用户或组。如果变量“users”包含一个组,这会引发异常吗? - Stefan Steiger
1
@StefanSteiger:在GetMembers()中的true标志指定了递归搜索,因此不会抛出错误。 - Muflix
显示剩余2条评论

15

这应该返回组中所有活动目录用户。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace ADQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            GetListOfAdUsersByGroup("domain", "group");
            Console.ReadLine();
        }

        public static void GetListOfAdUsersByGroup(string domainName, string groupName)
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://DC=" + domainName + ",DC=com");
            DirectorySearcher search = new DirectorySearcher(entry);
            string query = "(&(objectCategory=person)(objectClass=user)(memberOf=*))";
            search.Filter = query;
            search.PropertiesToLoad.Add("memberOf");
            search.PropertiesToLoad.Add("name");

            System.DirectoryServices.SearchResultCollection mySearchResultColl = search.FindAll();
            Console.WriteLine("Members of the {0} Group in the {1} Domain", groupName, domainName);
            foreach (SearchResult result in mySearchResultColl)
            {
                foreach (string prop in result.Properties["memberOf"])
                {
                    if (prop.Contains(groupName))
                    {
                        Console.WriteLine("    " + result.Properties["name"][0].ToString());
                    }
                }
            }
        }
    }
}

祝你好运!


不确定 (!(userAccountControl:1.2.840.113556.1.4.803:=2))(&(mail=*) 的意思是什么 - 我还需要按组进行过滤。 - raklos
抱歉,我匆忙中误读了你的问题,我发布了一些代码,应该更有帮助。 - Jive Boogie

3

Dalton的示例基础上,这里是获取组用户名的简洁代码:

static SortedSet<string> GetUsernames(string domainName, string groupName) {
  using (var pc = new PrincipalContext(ContextType.Domain, domainName))
  using (var gp = GroupPrincipal.FindByIdentity(pc, groupName))
    return gp == null ? null : new SortedSet<string>(
      gp.GetMembers(true).Select(u => u.SamAccountName));
}

3
以下代码将递归搜索嵌套域本地组和/或全局组以查找用户。您可以对其进行修改,以查找任何顺序的组以满足您的需求或返回任何想要的组。
// Set the list to return and get the group we are looking through.
List<UserPrincipal> list = new List<UserPrincipal>();
GroupPrincipal group = GroupPrincipal.FindByIdentity(new PrincipalContext(/* connection info here */), ((groupName.Length > 0) ? groupName : this.Properties.Name));

// For each member of the group add all Users.
foreach (Principal princ in group.Members)
{
    /*
    To change what you are looking for or how you are looking for it, 
    simply change some of the following conditions to match what you want.
    */

    // If this member is a User then add them.
    if (princ.StructuralObjectClass == "user")
    {
        list.Add(UserPrincipal.FindByIdentity(new PrincipalContext(/* connection info here */), princ.Name);
    }

    // If we are looking recursively and this member is a GL_Group then get the Users in it and add them.
    if (recursive && (princ.StructuralObjectClass == "group") && (((GroupPrincipal)princ).GroupScope == GroupScope.Global))
    {
        list.AddRange(this.GetUsers(true, princ.Name));
    }
}
return list;

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接