Подтвердить что ты не робот

Получить всех пользователей из группы в Active Directory

Я пытаюсь получить всех пользователей определенной группы в AD, а затем возвратить список Employees, сопоставленный свойствам в моем классе Employee. У меня есть:

Мой фильтр не производит никаких результатов - что это должно быть?

Кроме того, я попробовал первое решение здесь: Список пользователей в определенной группе распространения Active Directory, но мне нужны детали, такие как мобильный, расширение и т.д., которые я не мог получить с помощью этого метода.

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;
}
4b9b3361

Ответ 1

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

Ответ 2

Это должно вернуть всех пользователей Active Directory в группу.

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());
                    }
                }
            }
        }
    }
}

Удачи!

Ответ 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;

Ответ 4

Основываясь на примере 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));
}

Ответ 5

В этом сообщении я написал что-то, работающее в ActiveDirectory 2003 ans 2008 R2. Я использую Microsoft LDAP_MATCHING_RULE_IN_CHAIN ​​. Эта служба использует DirectoryServices. Будьте осторожны в этом коде, так как есть двойной поиск.

Но вы также можете сделать это с помощью "Управление принципами безопасности каталога" в .NET Framework 3.5. Вы можете прочитать этот другой пост. Вы должны получить GroupPrincipal, и вы ищете свойство Members. Он также содержит другие записи в StackOverflow.