user175084
user175084

Reputation: 4630

get computer name from active directory and OU's

i have a code to get all the computer names present in a doain which are not a part of any 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();

what i want is.. along with these computernames get the computer names that belong to different OU's within the domain...

any suggestions... thanks

Upvotes: 0

Views: 4403

Answers (1)

joe_coolish
joe_coolish

Reputation: 7259

You can try and do a nested for-loop. I did a small project where I added all the objects to a TreeView. Here is a snippet:

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

Upvotes: 1

Related Questions