C# - 如何使用 DirectorySearcher 限制对多个 OU 内特定部门的用户的搜索?

时间:2021-05-12 12:16:33

标签: c# active-directory directorysearcher

我们想根据多个 OU 查询特定部门用户的 Active Directory。

给定代码:

List<string> orgUnitsList= new List<string>(){"Banking","Support","Finance"};
List<ADUserInfo> adUsers = new List<ADUserInfo>();

foreach (var ou in orgUnitsList)
{
    // Construct the LDAP path and create instance of DirectorySearcher
    var ldap = $"LDAP://mydomain.local/OU={ou},DC=mydomain,DC=local";
    DirectoryEntry directoryEntry = new DirectoryEntry(ldap);
    DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);

    // Add PropertiesToLoad (for speeding up things)
    foreach (var propery in ADUserInfo.QueryProperties)
        directorySearcher.PropertiesToLoad.Add(property);

    // Set the filter and trigger FindAll()
    directorySearcher.Filter = "(&(objectClass=User)(department=" + searchString + "*))";
    SearchResultCollection searchResultCollection = directorySearcher.FindAll();

    Console.WriteLine($"{searchResultCollection.Count} users found for OU: {ou}");
    
    // Adding results to the returning list
    foreach (SearchResult u in searchResultCollection)
    {
        var user = new ADUserInfo(u);
        adUsers.Add(user);
    }
}
return adUsers;

这种方法简单吗? 我们做错了什么? 将 OU 添加到过滤器是为了加快查询速度,因为查询需要很长时间(超过一分钟并达到超时),同样通过添加 PropertiesToLoad..

用于搜索用户的过滤器在 2 秒内返回数百个项目:

directorySearcher.Filter = "(&(objectClass=User)(|(displayName=" + searchString + "*)))";

感谢任何帮助!

0 个答案:

没有答案
相关问题