在 Active Directory 组中通过查询查找用户

Find Users by Query inside a Active Directory Group

给定一个包含很多成员的特定组,我想在组内查询以查找具有 DisplayName 匹配的成员。

下面的代码是我想要完成的非功能性示例。请注意,我不想先加载整个列表然后再应用 'where',我已经可以这样做了,而且速度很慢,因为组很大。

    public static List<Principal> FindUsersOfGroup(string groupName, string displayNameQuery)
    {
        using (var context = new PrincipalContext(ContextType.Machine, Environment.MachineName))
        {
            var search = new GroupPrincipal(context);
            search.SamAccountName = groupName;
            // This where doesn't work, but is what I'm looking for.
            search.Members.Where(m => m.DisplayName == displayNameQuery + "*");

            using (var ps = new PrincipalSearcher(search))
            {
                // Want to get all members that match the query AND belong to the group.
                return ps.FindAll().ToList();
            }
        }
    }

另外,context在我的真实代码中是Domain,我是故意替换的。

你可以用 DirectorySearcher class:

using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + Environment.UserDomainName))
{
    using (DirectorySearcher searcher = new DirectorySearcher(
        entry,
        string.Format(
            "(&(objectCategory=person)(objectClass=user)(displayName={0}*)(memberof={1}))",
            displayNameQuery,
            groupName)))
    {

        searcher.PropertiesToLoad.Add("samAccountname"); //You can specify which properties you want to load. If you don't specify properties, by default you will get a lot of properties. Loading specific properties is better in terms of performance

        using (var results = searcher.FindAll())
        {
            foreach (var result in results.Cast<SearchResult>())
            {
                //Do something with result
                var properties = result.Properties;

                //Example
                var samAccountName = properties["samAccountName"][0];
                //...
            }
        }
    }
}

groupName 在这种情况下是组的可分辨名称(例如 CN=Administrators,CN=Builtin,DC=dnb,DC=lab)