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

C# 在Active Directory中搜索所有匹配的对象,c#,winforms,active-directory,directoryservices,C#,Winforms,Active Directory,Directoryservices,目标:我想使用System.DirectoryServices.AccountManagement命名空间查询用户和计算机对象的AD。(示例:搜索关键字“Test”,我将返回包含“Test”的用户帐户和计算机帐户) 目前我使用以下两种方法来实现这一点。如果可能的话,我想将这两种方法合并成一个单独的方法。我尝试过使用AdvancedFilters类,但没有成功=( 我正在寻找的另一个例子是:在使用AD模块的PowerShell中,我能够使用如下命令Get-ADObject-Filter'SamAc

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

  • 目前我使用以下两种方法来实现这一点。如果可能的话,我想将这两种方法合并成一个单独的方法。我尝试过使用
    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 GetADComputer(字符串pcName)
    {
    PrincipalContext ctx=新PrincipalContext(ContextType.Domain);
    ComputerPrincipal computer=新的ComputerPrincipal(ctx);
    computer.Name=String.Format(“*{0}*”,pcName);
    PrincipalSearcher=新PrincipalSearcher();
    searcher.QueryFilter=计算机;
    返回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();
        }
    
    public PrincipalSearchResult GetADUser(字符串用户名)
    {
    PrincipalContext ctx=新PrincipalContext(ContextType.Domain);
    UserPrincipal用户=新的UserPrincipal(ctx);
    user.SamAccountName=String.Format(“*{0}*”,用户名);
    PrincipalSearcher=新PrincipalSearcher();
    searcher.QueryFilter=用户;
    返回searcher.FindAll();
    }
    
    我不确定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();
    

    谢谢你的回复。我真的想把我所有与广告相关的代码都保存到AccountManagement类中。如果我找不到任何其他方法,我会使用这些代码。