【问题标题】:Search Active Directory for all matching objects在 Active Directory 中搜索所有匹配的对象
【发布时间】:2023-08-02 17:47:02
【问题描述】:
  • 目标:我想使用 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<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();
    }

【问题讨论】:

    标签: c# winforms active-directory directoryservices


    【解决方案1】:

    我不确定 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();
    

    【讨论】:

    • 感谢您的回复。我真的想将所有与 AD 相关的代码保留在 AccountManagement 类中。如果我找不到任何其他方式,我将诉诸此代码。
    最近更新 更多