使用System.DirectoryServices.AccountManagement在c#中搜索与特定名称匹配的所有

本文关键字:定名称 搜索 DirectoryServices System AccountManagement 使用 | 更新日期: 2023-09-27 18:22:02

似乎System.DirectoryServices.AccountManagement提供了一次只能搜索一种类型对象的示例查询。

System.DirectoryServices.AccountManagement是否证明了一种方法,使用该方法我可以在整个active directory中搜索与特定名称或某些其他条件匹配的用户或组,或者我必须返回System.DirectoryServices.DirectorySearcher.

使用System.DirectoryServices.AccountManagement在c#中搜索与特定名称匹配的所有

我相信你应该能够在S.DS.AM中做到这一点。UserPrincipalGroupPrincipal最终都是从Principal派生而来的,所以如果你将"通用"主体传递给搜索者,你应该同时得到用户和组(以及计算机)。

唯一棘手的部分是Principal是一个抽象类,所以你不能直接实例化它——你需要先得到一个UserPrincipal,然后从中"提取"通用的Principal

// set up dummy UserPrincipal
UserPrincipal qbeUser = new UserPrincipal(ctx);
// get the generic Principal from that - set the "Name" to search for
Principal userOrGroup = qbeUser as Principal;
userOrGroup.Name = "SomeName";
// create a PrincipalSearcher based on that generic principal
PrincipalSearcher searcher = new PrincipalSearcher(userOrGroup);
// enumerate the results - you need to check what kind of principal you get back
foreach (Principal found in searcher.FindAll())
{
    // is it a UserPrincipal - do what you need to do with that...
    if (found is UserPrincipal)
    {
        ......
    }
    else if (found is GroupPrincipal)
    {
        // if it's a group - do whatever you need to do with a group....
    }
 }