[英]LDAP filter string for Active Directory Users and Computers “find” dialogue
[英]Find computers in active directory
當我使用dsa.msc手動搜索計算機並打開其屬性時,有一個“位置”選項卡。 它可能有也可能沒有價值。 當我嘗試使用.Net的目錄服務獲取此信息時,我沒有看到“位置”屬性。 我打印出所有可用的屬性,但沒有看到它。 它是不可用還是我錯過了什么? 這是部分代碼:
string sADPath = "LDAP://blah.blah.com";
DirectoryEntry de = new DirectoryEntry(sADPath);
string sFilter = "(&(objectCategory=computer)(name=" + sComputerName + "))";
DirectorySearcher DirectorySearch = new DirectorySearcher(de, sFilter);
SearchResult DirectorySearchResult = DirectorySearch.FindOne();
if (null != DirectorySearchResult)
{
DirectoryEntry deComp = DirectorySearchResult.GetDirectoryEntry();
oComputer.CN = deComp.Properties["cn"].Value.ToString();
....
}
編輯:
我誤解了這個要求! 它不是我需要的計算機的“物理”位置,而是AD層次結構中的位置。 似乎應該在“abc.org - > A - > B”中的計算機不存在,但位於“abc.org - > A - > C - > D”。 我需要的是能夠在給定計算機名稱的情況下找到路徑“abc.org - > A - > C - > D”。
屬性名稱是“位置”。 與所有AD屬性一樣,如果搜索結果對象沒有值,則不會在搜索結果對象上看到它。 我已經擺弄了你的代碼,以便它可以在我的機器上工作。
如果您只是檢索數據而不打算進行任何更改,則無需調用GetDirectoryEntry(這將對服務器進行另一次往返)。 請注意語法上的細微差別:
var rootDSE = new DirectoryEntry("LDAP://RootDSE");
var defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString();
var domainRootADsPath = String.Format("LDAP://{0}", defaultNamingContext);
var searchRoot = new DirectoryEntry(domainRootADsPath);
var filter = "(&(objectCategory=computer)(name=" + computerName + "))";
var directorySearch = new DirectorySearcher(searchRoot, filter);
var directorySearchResult = directorySearch.FindOne();
if (null != directorySearchResult)
{
Console.WriteLine(directorySearchResult.Properties["cn"][0].ToString());
if (directorySearchResult.Properties["location"].Count > 0)
{
Console.WriteLine(directorySearchResult.Properties["location"][0].ToString());
}
//It's not necessary to run GetDirectoryEntry unless you want to make a change
DirectoryEntry deComp = directorySearchResult.GetDirectoryEntry();
Console.WriteLine(deComp.Properties["cn"].Value.ToString());
if (deComp.Properties["location"].Value != null)
{
Console.WriteLine(deComp.Properties["location"].Value.ToString());
}
}
您可以嘗試在所有結果中運行搜索:
SearchResultCollection results = DirectorySearch.FindAll();
foreach(SearchResult res in results)
{
string[] temp = res.Path.Split(','); // temp[0] would contain the computer name
if(temp[0].Equals("...")) // ...
}
或者,嘗試
string sFilter = "(&(objectCategory=computer)(computerName=" + sComputerName + "))";
將“name”替換為“computerName”
如果要按主機DNS名稱查找AD條目,請嘗試使用以下命令:
using (var de = new DirectoryEntry("LDAP://domain.ru"))
{
var search = new DirectorySearcher(de, (string.Format("(dNSHostName={0})", hostName)));
foreach (SearchResult i in search.FindAll())
{
return new MAdHost()
{
Name = hostName,
Path = i.Path
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.