2010-05-27 104 views
2

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

 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); 
     } 

非常感谢。

回答

2

如果你可以升级到.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(); 

你需要指数.Properties["name"]集合与[0]获得的第一项(通常也是唯一的入口 - 几乎没有任何计算机有多个名称)。

+0

我刚刚在添加了[0]之前,我读了你的文章,工作就像一个治疗:)再次感谢马克。 我将不得不做一些阅读收藏属性,因为我真的不明白他们是什么,或者当我处理一组对象时如何解决。 – 2010-05-27 13:28:45

+0

我实际上使用的是.Net 3.5,我只是没有关于如何使用.AccountManagement命名空间的模糊想法,虽然它会是我看看的东西,因为我希望扩展我正在写的应用程序,当我得到一些更多的时间,现在最低限度会做我需要的星期一:) – 2010-05-27 13:33:23

+0

@Stephen Murby:绝对读MSDN文章 - 优秀的东西! – 2010-05-27 14:43:58

相关问题