我想使用C#在域中搜索特定的计算机。我必须搜索类似于以下示例的子树:
公司计算机
我已经尝试研究此问题,但是我发现的所有示例要么寻找我不知道的特定路径,要么搜索整个域。
我想我正在寻找与Get-ADComputer等效的C#。
答案 0 :(得分:0)
在MSDN C#论坛的互动之后,cheong00提供了以下帮助:
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
public static void FindComputer(string computerHostName)
{
DirectoryContext dirCtx = new DirectoryContext(DirectoryContextType.Domain, "domain.lan");
using (Domain usersDomain = Domain.GetDomain(dirCtx))
using (DirectorySearcher adsearcher = new DirectorySearcher(usersDomain.GetDirectoryEntry()))
{
adsearcher.Filter = "(&(objectClass=computer) (cn=" + computerHostName + "))";
adsearcher.SearchScope = SearchScope.Subtree;
adsearcher.PropertiesToLoad.Add("description");
SearchResultCollection searchResults = adsearcher.FindAll();
foreach (SearchResult searchResult in searchResults)
{
Console.WriteLine(searchResult.Properties["adspath"][0]);
}
}
}
我对其进行了一些修改,以提供以下信息,现在它检查是否存在我想要的计算机:
DirectoryContext dirCtx = new DirectoryContext(DirectoryContextType.Domain, "domain.lan");
using (Domain usersDomain = Domain.GetDomain(dirCtx))
using (DirectorySearcher adsearcher = new DirectorySearcher(usersDomain.GetDirectoryEntry()))
{
adsearcher.Filter = "(&(objectClass=computer) (cn=" + computerHostName + "))";
adsearcher.SearchScope = SearchScope.Subtree;
adsearcher.PropertiesToLoad.Add("description");
SearchResult searchResults = adsearcher.FindOne();
if (searchResults.ToString().Length <= 0)
{
//nothing found
Console.Write("Cannot find");
}
else
{
Console.Write("Found");
}
}
谢谢大家的帮助:)