列出活动目录中的所有计算机
我想知道如何从活动目录中获取所有计算机/机器/ PC的列表?
(试图让这个页面成为搜索引擎诱饵,会回复自己。如果有人有更好的回复,我会接受)
如果您有一个非常大的域,或者您的域在每次搜索可以返回多少项的配置限制,您可能必须使用分页。
using System.DirectoryServices; //add to references public static List GetComputers() { List ComputerNames = new List (); 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中列出所有对象时,这会大大降低性能。
如果您只需要查询AD,最好只使用结果对象的Properties
集合。 这将多次提高代码的性能。
SearchResult
类的文档中对此进行了解释:
SearchResult
类的实例与DirectoryEntry
类的实例非常相似。 关键的区别在于DirectoryEntry
类每次访问新对象时都会从Active Directory域服务层次结构中检索其信息,而SearchResult
的数据在SearchResult
中已经可用,它从使用该查询执行的查询中返回DirectorySearcher
类。
以下是有关如何使用Properties
集合的示例 :
public static List GetComputers() { List computerNames = new List (); 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
子句完成。
像: (objectCategory=computer)
这样的LDAP查询应该可以解决问题。
- 如何从C#中找到活动目录中的用户?
- ASP.NET – 获取DirectoryEntry / SID的主体/相对标识符(RID)
- C#ADAL AcquireTokenAsync()没有弹出框
- Active Directory:调整函数的性能以检索组成员
- 使用C#从ASP.Net MVC访问Active Directory
- 即使pagesize设置为更大,directorysearcher对象的上限是5000
- ASP.NET / Active Directory – 支持域用户的自动登录
- 如果OU包含3000个用户,如何使用DirectorySearcher查找所有用户?
- UserPrincipal.GetGroups与UserPrincipal.GetAuthorizationGroups?