在活动目录中查找计算机

时间:2013-11-29 15:46:52

标签: c# active-directory directoryservices

当我使用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 - &gt ; D“。我需要的是能够在给定计算机名称的情况下找到路径“abc.org - > A - > C - > D”。

3 个答案:

答案 0 :(得分:6)

属性名称是“位置”。与所有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());
    }
}

答案 1 :(得分:0)

您可以尝试在所有结果中运行搜索:

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 + "))";

替换"名称"通过" computerName"

答案 2 :(得分:0)

如果要按主机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
                    };
            }

        }