从活动目录和OU获取计算机名称

时间:2011-02-28 22:22:55

标签: c# asp.net active-directory dns

我有一个代码来获取doain中存在的所有计算机名称,这些名称不属于任何OU。

DirectoryEntry entry = new DirectoryEntry("LDAP://" + "Domain Name");
        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);
            compList.Add(ComputerName);
        }

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

我想要的是......以及这些计算机名称获取属于域内不同OU的计算机名称...

任何建议......谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试执行嵌套for循环。我做了一个小项目,我将所有对象添加到TreeView中。这是一个片段:

    public delegate void Del(TreeNode node);

    public window_main()
    {
        InitializeComponent();
        Thread t = new Thread(load_ad);
        t.Start();
    }

    private void addNode(TreeNode node)
    {
        treeViewObjects.Nodes.Add(node);
    }
    private void load_ad()
    {
        TreeNode root = new TreeNode(directoryEntry.Name.Replace("\\", ""));
        root.Tag = directoryEntry;

        Del del = addNode;
        treeViewObjects.Invoke(del, root);

        foreach (DirectoryEntry myChildDirectoryEntry in directoryEntry.Children)
        {
            TreeNode node = rec(myChildDirectoryEntry);

            treeViewObjects.Invoke(new Action(() =>
            {
                root.Nodes.Add(node);
            }));
        }
    }
    private TreeNode rec(DirectoryEntry dir)
    {
        TreeNode node = new TreeNode(dir.Name.Replace("\\", ""));
        node.Tag = dir;
        foreach (DirectoryEntry myChildDirectoryEntry in dir.Children)
        {
            try
            {
                node.Nodes.Add(rec(myChildDirectoryEntry));
            }
            catch
            {
                TreeNode nodeChild = new TreeNode(dir.Name.Replace("\\", ""));
                nodeChild.Tag = myChildDirectoryEntry;
                node.Nodes.Add(nodeChild);
            }
        }
        return node;
    }