使用 PrincipalSearcher 获取 AD 组中的成员计数

本文关键字:成员 PrincipalSearcher 获取 AD 使用 | 更新日期: 2023-09-27 18:32:37

Env : Visual Studio 2013, FrameWork 4.5, Telerik Controls, C#, WebForm application

使用 : System.DirectoryServices

和 System.DirectoryServices.AccountManagement

我正在制作一个搜索工具,以便用户可以在多个林/域中搜索活动目录组名称。

搜索返回 1 个或多个组的列表,我将该列表放在 RadGrid (Telerik) 中。网格的每一行都是一个 AD 组。我想显示一个附加信息,向用户显示该组中有多少(计数?)成员(用户)。

private List<AdGroup> GetListOfGroupAD(string domain, string name, string samAccountName)
    {
        try
        {
            GroupPrincipal qbeGroup;
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain))
            {
                qbeGroup = new GroupPrincipal(ctx);
                qbeGroup.Name = !string.IsNullOrEmpty(name) ? name : "*";
                qbeGroup.SamAccountName = !string.IsNullOrEmpty(samAccountName) ? samAccountName : "*";
                PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
                ((DirectorySearcher)srch.GetUnderlyingSearcher()).PageSize = 500;
                List<AdGroup> listeGroupe = srch.FindAll()
                                      .OrderBy(x => x.SamAccountName)
                                      .Select(x => new AdGroup()
                                      {
                                          SamAccountName = x.SamAccountName,
                                          Description = x.Description,
                                          Domain = domain,
                                          NbMember = 0 //Can i Get a count of members in group here ?????
                                      })
                                      .ToList();
                return listeGroupe;
            }
        }
        catch (ArgumentNullException ex)
        {
            writeToLog(ex.Message, 1);
            return null;
        }
        catch (Exception ex)
        {
            writeToLog(ex.Message, 1);
            return null;
        }
    }
public class AdGroup
    {
        public string SamAccountName { get; set; }
        public string Description { get; set; }
        public string Domain { get; set; }
        public int NbMember { get; set; }
    }

谢谢你的帮助

理查

使用 PrincipalSearcher 获取 AD 组中的成员计数

一种方法是在调用 FindAll() 后使用 .OfType() 将搜索结果的类型指定为 GroupPrincipal,然后可以使用 Members 集合属性或 GetMembers() 方法获取每个组的成员作为集合,该方法具有可选的布尔参数,用于指定是否需要递归搜索组以查找嵌套成员。此时,获取集合的大小。

List<AdGroup> listeGroupe = srch.FindAll()
    .OfType<GroupPrincipal>()
    .OrderBy(x => x.SamAccountName)
    .Select(x => new AdGroup()
    {
        SamAccountName = x.SamAccountName,
        Description = x.Description,
        Domain = domain,
        NbMember = x.Members.Count
    })
    .ToList();