如何使用 LDAP 和 C# 搜索用户 ID 列表?

How do I search for a list of user id's using LDAP and C#?

我需要根据特定的用户 ID 列表搜索用户。如果我使用此过滤器搜索单个用户,效果很好:

 using (DirectorySearcher ds = new DirectorySearcher(de) { Filter = $"(&(sAMAccountType=805306368)(sAMAccountName=xyz123))" })
 {
    SearchResult sr = ds.FindOne();
 }

我找到了这个LDAP Filter Syntax page,它表明条件可以嵌套。

(|(cn=Jim Smith)(&(givenName=Jim)(sn=Smith)))

Conditions can be nested with parentheses, but make sure the parentheses match up.

所以我尝试使用这个过滤器和 FindAll(),虽然我希望看到我们的 1 个和加拿大的 1 个,但它只在加拿大找到了一个。

(&(sAMAccountType=805306368)(!(sAMAccountName=xyz123)(sAMAccountName=abc456)))

Searching domain: us

Count: 0

Searching domain: canada

Count: 1

也许我对过滤器语法的理解还不够。另外,是否可以一键搜索所有域名?

您使用的是感叹号 (!),表示 "not"。你想使用管道 (|),这意味着 "or":

(&(sAMAccountType=805306368)(|(sAMAccountName=xyz123)(sAMAccountName=abc456)))

如果您有大量要查找的用户名(我说的是数百个),您可能会考虑将它们分成单独的搜索。我实际上在一篇关于此的文章中介绍了这个(带有示例代码):Active Directory: Better performance