列出活动目录中的所有计算机

问题描述:

我想知道如何从活动目录中获取所有计算机/机器/ pc的列表?列出活动目录中的所有计算机

(试图让这个页面搜索引擎诱饵,会回复自己。如果有人有更好的回答金正日接受)

如果你有一个非常大的领域,或者您的域名已经就如何如何配置的限制许多项目可以被返回每个搜索,你可能不得不使用分页。

using System.DirectoryServices; //add to references 

public static List<string> GetComputers() 
{ 
    List<string> ComputerNames = new List<string>(); 

    DirectoryEntry entry = new DirectoryEntry("LDAP://YourActiveDirectoryDomain.no"); 
    DirectorySearcher mySearcher = new DirectorySearcher(entry); 
    mySearcher.Filter = ("(objectClass=computer)"); 
    mySearcher.SizeLimit = int.MaxValue; 
    mySearcher.PageSize = int.MaxValue; 

    foreach(SearchResult resEnt in mySearcher.FindAll()) 
    { 
     //"CN=SGSVG007DC" 
     string ComputerName = resEnt.GetDirectoryEntry().Name; 
     if (ComputerName.StartsWith("CN=")) 
      ComputerName = ComputerName.Remove(0,"CN=".Length); 
     ComputerNames.Add(ComputerName); 
    } 

    mySearcher.Dispose(); 
    entry.Dispose(); 

    return ComputerNames; 
} 

LDAP查询像:(objectCategory = computer)应该做的伎俩。 -Jim

什么EKS建议是正确的,但在执行一点点

原因是每个结果对GetDirectoryEntry()的调用。这会创建一个DirectoryEntry对象,只有在需要修改活动目录(AD)对象时才需要该对象。如果您的查询将返回单个对象,但是在AD中列出所有对象时,这可以大大降低性能。

如果您只需要查询AD,最好只使用结果对象的Properties集合。这会多次提高代码的性能。

这在documentation for SearchResult class解释说:

SearchResult类的实例非常相似 DirectoryEntry类的实例。关键的区别是, DirectoryEntry类从Active Directory域服务层次中的每个新的对象 访问时,获取其信息,而对于SearchResult的数据已经在 的SearchResultCollection,它会从一个查询返回可用的 与DirectorySearcher类一起执行。

下面是关于如何使用Properties集合的例如

public static List<string> GetComputers() 
{ 
    List<string> computerNames = new List<string>(); 

    using (DirectoryEntry entry = new DirectoryEntry("LDAP://YourActiveDirectoryDomain.no")) { 
     using (DirectorySearcher mySearcher = new DirectorySearcher(entry)) { 
      mySearcher.Filter = ("(objectClass=computer)"); 

      // No size limit, reads all objects 
      mySearcher.SizeLimit = 0; 

      // Read data in pages of 250 objects. Make sure this value is below the limit configured in your AD domain (if there is a limit) 
      mySearcher.PageSize = 250; 

      // Let searcher know which properties are going to be used, and only load those 
      mySearcher.PropertiesToLoad.Add("name"); 

      foreach(SearchResult resEnt in mySearcher.FindAll()) 
      { 
       // Note: Properties can contain multiple values. 
       if (resEnt.Properties["name"].Count > 0) 
       { 
        string computerName = (string)resEnt.Properties["name"][0]; 
        computerNames.Add(computerName); 
       } 
      } 
     } 
    } 

    return computerNames; 
} 

Documentation for SearchResult.Properties

注意,属性可以有多个值,这就是为什么我们使用Properties["name"].Count检查该号码值。

为了进一步改进,请使用PropertiesToLoad集合让搜索者事先知道要使用的属性。这使得搜索者只能读取实际将要使用的数据。

注意,DirectoryEntryDirectorySearcher对象应该 得到妥善处置,以释放使用的所有资源。其最好的 完成using条款。