我想知道如何从Active Directory中的所有计算机/计算机/ PC的列表?
(试图让这个页面搜索引擎诱饵,会回复自己。如果有人有更好的回答金正日接受)
我想知道如何从Active Directory中的所有计算机/计算机/ 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;
}
什么EKS建议是正确的 ,但在执行有点慢 。
其原因是调用GetDirectoryEntry()
上的每个结果。 这将创建一个DirectoryEntry
对象,如果你需要修改活动目录(AD)对象时,才需要。 这是确定的,如果你的查询将返回一个对象,但在公元列出所有对象时,这极大地降低了性能。
如果你只需要查询AD,它能够更好地只使用Properties
的结果对象的集合。 这将提高代码几次的性能。
这在解释对文件SearchResult
类 :
该实例
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;
}
文档SearchResult.Properties
请注意,属性可以有多个值,这就是为什么我们使用Properties["name"].Count
检查值的数量。
为了进一步改善的事情,使用PropertiesToLoad
集合,让搜索者知道你要事先要使用什么样的属性。 这使得搜索设置为只读,实际上是将要使用的数据。
注意
DirectoryEntry
和DirectorySearcher
对象应妥善处置,以释放使用的所有资源。 它最好用做using
条款。
像LDAP查询: (objectCategory=computer)
应该做的伎俩。