在Active Directory中搜索所有匹配的对象

时间:2014-03-17 19:14:26

标签: c# winforms active-directory directoryservices

  • 目标:我想使用System.DirectoryServices.AccountManagement命名空间为用户和计算机对象查询AD。 (示例:搜索关键字"测试",我将返回包含"测试"的用户帐户和计算机帐户;)

  • 目前我使用以下两种方法来实现这一目标。如果可能的话,我想将这两种方法合二为一。我尝试过AdvancedFilters课,但没有成功=(

  • 我正在寻找的另一个例子:在使用AD模块的PowerShell中,我能够使用像Get-ADObject -Filter 'SamAccountName -like "*test*"'这样的命令来完全满足我的需要。

查询计算机:

    public PrincipalSearchResult<Principal> GetADComputer(string pcName)
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);            
        ComputerPrincipal computer = new ComputerPrincipal(ctx);
        computer.Name = String.Format("*{0}*", pcName);

        PrincipalSearcher searcher = new PrincipalSearcher();
        searcher.QueryFilter = computer;

        return searcher.FindAll();
    }

查询用户

    public PrincipalSearchResult<Principal> GetADUser(string userName)
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

        UserPrincipal user = new UserPrincipal(ctx);
        user.SamAccountName = String.Format("*{0}*", userName);

        PrincipalSearcher searcher = new PrincipalSearcher();
        searcher.QueryFilter = user;

        return searcher.FindAll();
    }

1 个答案:

答案 0 :(得分:2)

我不确定AccountManagement,但我会使用DirectoryServices来实现:

DirectoryEntry de = new DirectoryEntry("LDAP://myldapserver.com");
DirectorySearcher directorySearcher = new DirectorySearcher(de);
directorySearcher.Filter = "(&(|(objectclass=user)(objectclass=computer))(samaccountname=*"+objectName+"*))";
SearchResultCollection srCollection = directorySearcher.FindAll();