【发布时间】: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