List all computers in active directory

后端 未结 3 371
你的背包
你的背包 2020-12-05 11:41

Im wondering how to get a list of all computers / machines / pc from active directory?

(Trying to make this page a search engine bait, will reply myself. If someone

3条回答
  •  囚心锁ツ
    2020-12-05 12:13

    If you have a very big domain, or your domain has limits configured on how how many items can be returned per search, you might have to use paging.

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

提交回复
热议问题