【问题标题】:Get machine name from Active Directory从 Active Directory 获取机器名称
【发布时间】:2010-05-27 13:10:04
【问题描述】:

我已执行“LDAP://”查询以获取指定 OU 中的计算机列表,我的问题是无法仅收集计算机“名称”甚至“cn”。

        DirectoryEntry toShutdown = new DirectoryEntry("LDAP://" + comboBox1.Text.ToString());
        DirectorySearcher machineSearch = new DirectorySearcher(toShutdown);
        //machineSearch.Filter = "(objectCatergory=computer)";
        machineSearch.Filter = "(objectClass=computer)";
        machineSearch.SearchScope = SearchScope.Subtree;
        machineSearch.PropertiesToLoad.Add("name");
        SearchResultCollection allMachinesCollected = machineSearch.FindAll();
        Methods myMethods = new Methods();
        string pcName;
        foreach (SearchResult oneMachine in allMachinesCollected)
        {
            //pcName = oneMachine.Properties.PropertyNames.ToString();
            pcName = oneMachine.Properties["name"].ToString();
            MessageBox.Show(pcName);
        }

非常感谢您的帮助。

【问题讨论】:

    标签: active-directory ldap


    【解决方案1】:

    如果您可以升级到 .NET 3.5,我绝对建议您这样做。

    在 .NET 3.5 中,您会获得一个新的 System.DirectoryServices.AccountManagement 命名空间,这使得其中很多工作变得更加容易。

    要查找所有计算机并枚举它们,您可以执行以下操作:

    // define a domain context - use your NetBIOS domain name
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
    
    // set up the principal searcher and give it a "prototype" of what you want to
    // search for (Query by Example) - here: a ComputerPrincipal
    PrincipalSearcher srch = new PrincipalSearcher();
    srch.QueryFilter = new ComputerPrincipal(ctx);;
    
    // do the search
    PrincipalSearchResult<Principal> results = srch.FindAll();
    
    // enumerate over results
    foreach(ComputerPrincipal cp in results)
    {
       string computerName = cp.Name;
    }
    

    查看 MSDN 杂志上的 Managing Directory Security Principals in the .NET Framework 3.5,了解有关新的 S.DS.AM 命名空间及其提供的功能的更多信息。

    如果您无法升级到 .NET 3.5 - 您只需记住您从搜索结果中获得的 .Properties["name"] 是一个值集合 - 所以按顺序要获取实际的电脑名称,请使用:

    pcName = oneMachine.Properties["name"][0].ToString();
    

    您需要使用[0] 索引.Properties["name"] 集合以获取第一个条目(通常也是唯一的条目 - 几乎没有任何计算机有多个名称)。

    【讨论】:

    • 我刚刚在阅读您的帖子之前添加了 [0],工作就像一种享受 :) 再次感谢 Marc。我将不得不对收藏品进行一些阅读,例如属性,因为我还不太了解它们是什么,或者在处理对象集合时如何解决。
    • 我实际上正在使用 .Net 3.5 我只是对如何使用 .AccountManagement 命名空间一无所知,尽管我希望扩展应用程序时会看看它当我有更多时间的时候我会写,现在最低限度的会在我需要的时候做星期一:)
    • @Stephen Murby:一定要阅读 MSDN 文章 - 好东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多