我试图运行一个LDAP查询将返回其所属的组织单位的所有用户OU=Employees
,并OU=FormerEmployees
和我没有任何地方获得.
我尝试使用,distinguishedName
但似乎不支持通配符.我知道必须有一个更简单的方法,但我的搜索努力没有产生任何结果
mar*_*c_s 10
如果您使用的是.NET 3.5及更高版本,则可以使用a PrincipalSearcher
和"按示例查询"主体进行搜索:
// create your domain context and define what container to search in - here OU=Employees
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=Employees,DC=YourCompany,DC=com");
// define a "query-by-example" principal - here, we search for a UserPrincipal
// that is still active
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Enabled = true;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
Run Code Online (Sandbox Code Playgroud)
如果您还没有 - 绝对阅读MSDN文章.NET Framework 3.5中的管理目录安全主体,它很好地展示了如何充分利用新功能System.DirectoryServices.AccountManagement
如果您更喜欢"旧的".NET 2.0样式,则需要创建一个DirectoryEntry
与要枚举对象的OU对应的基础,然后您需要创建一个DirectorySearcher
搜索对象的基础 - 如下所示:
// create your "base" - the OU "FormerEmployees"
DirectoryEntry formerEmployeeOU = new DirectoryEntry("LDAP://OU=FormerEmployees,DC=YourCompany,DC=com");
// create a searcher to find objects inside this container
DirectorySearcher feSearcher = new DirectorySearcher(formerEmployeeOU);
// define a standard LDAP filter for what you search for - here "users"
feSearcher.Filter = "(objectCategory=user)";
// define the properties you want to have returned by the searcher
feSearcher.PropertiesToLoad.Add("distinguishedName");
feSearcher.PropertiesToLoad.Add("sn");
feSearcher.PropertiesToLoad.Add("givenName");
feSearcher.PropertiesToLoad.Add("mail");
// search and iterate over results
foreach (SearchResult sr in feSearcher.FindAll())
{
// for each property, you need to check where it's present in sr.Properties
if (sr.Properties["description"] != null && sr.Properties["description"].Count > 0)
{
string description = sr.Properties["description"][0].ToString();
}
}
Run Code Online (Sandbox Code Playgroud)