c# - Active Directory - 获取多个广告组中的所有用户

标签 c# active-directory directoryservices

有没有办法获取多个组中的所有活跃用户?

例如:

Get all active users in "AdGroupA" OR "AdGroupB" OR "AdGroupC"

我看到过关于单个组的帖子,但没有看到多个组的帖子。

谢谢。

最佳答案

如果我理解正确的话,您只想返回多个组中的整个用户列表?这应该像多次从单个组中获取用户一样简单。

public IEnumerable<UserPrincipal> GetUsersFromGroups(string[] groupNames)
{
    using (var ctx = new PrincipalContext(ContextType.Domain))
    {
        foreach (var groupName in groupNames)
        {
            foreach (var userPrincipal in GroupPrincipal.FindByIdentity(ctx, groupName)
                                               .GetMembers())
            {
                yield return userPrincipal;
            }
        }       
    }
}    

这是一个不使用AccountManagement的方法:

using System.DirectoryServices;

public static IEnumerable<DirectoryEntry> GetUsersFromGroups(string[] groupNames)
{
    if (groupNames.Length > 0)
    {
        var searcher = new DirectorySearcher();
        string searchFilter = "(&(objectClass=Group)"; //filter for groups
        searchFilter += "(|"; //start a group of or parameters

        foreach (var group in groupNames)  // loop through the group names
        {
            searchFilter += string.Format("(SAMAccountName={0})",group); //add a parameter for each group in the list
        }

        searchFilter += "))"; //close off the filter string
        searcher.Filter = searchFilter; //add the filter to the searcher

        searcher.PropertiesToLoad.Add("member"); // load the members property for the group

        var searchResults = searcher.FindAll(); // perform the search

        foreach (SearchResult result in searchResults)
        {
            var directoryEntry = (DirectoryEntry)result.GetDirectoryEntry(); // get the directory entry for the group
            PropertyValueCollection members = directoryEntry.Properties["member"]; // get the members collection

            foreach (string name in members)   // iterate over the members. This string will be the distinguished name
            {
                yield return new DirectoryEntry(string.Format("LDAP://{0}",name)); //return the directory entry. You may get the entry and return the display name or just return distinguished name.
            }
        }
    }        
}

在我的环境中,我发现这比对 1 个组使用 DirectoryServices.AccountManagement 平均快 25% 左右,但随着组和用户数量的增加,AccountManagement > 方法实际上变得更快了。这仅查询 AD 一次,而第一种方法每组查询一次。

关于c# - Active Directory - 获取多个广告组中的所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032672/

相关文章:

c# - 如何自动改变kinect传感器角度?

c++ - 写入远程 Windows 共享文件夹的所有者时,GetNamedSecurityInfo 返回 ERROR_ACCESS_DENIED(5)

active-directory - Azure 应用服务 Active Directory 身份验证访问被拒绝

c# - 使用 Windows 身份验证创建 PrincipalContext

c# - 给定用户的 SID,我如何获得他们的 userPrincipalName?

c# - 异步和 FromAsync

c# - 如何配置 XmlDocument

c# - 在 C# 中,HttpClient.getStringAsync() 方法的同步替代方法是什么?

c# - 安装项目不包含库 : System. 此平台不支持 DirectoryServices.AccountManagement

windows - Active Directory - 用于查找不在一组组中的所有用户的脚本?