列出活动目录中的所有计算机
如果你有一个非常大的领域,或者您的域名已经就如何如何配置的限制许多项目可以被返回每个搜索,你可能不得不使用分页。
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
集合让搜索者事先知道要使用的属性。这使得搜索者只能读取实际将要使用的数据。
注意,
DirectoryEntry
和DirectorySearcher
对象应该 得到妥善处置,以释放使用的所有资源。其最好的 完成using
条款。