Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get active directory computers of specific group using "memberOf" attribute using C#

I'm trying to get all the computer names which are in the active directory "Standard" group. The AD tree looks like this:

adtree

I tried to get the computers using "memberOf" attribute (I found the attributes on this page: http://www.kouti.com/tables/userattributes.htm). So I have this code:

using (var context = new PrincipalContext(ContextType.Domain, "bbad.lan"))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry entry = result.GetUnderlyingObject() as DirectoryEntry;

            if (entry.Properties["memberOf"].Value == "Computer")
            {
                MessageBox.Show("aaa: " + entry.Properties["Name"].Value.ToString());
            }
        }
    }
}

After debugging this code because it didn't show any message boxes I found out that the "memberOf" attribute returns some strange strings. I used MessageBox.Show(entry.Properties["memberOf"].Value.ToString()); to get the value of "memberOf" attribute. This is what I get:

1. MsgBox: CN=Gäste,CN=Builtin,DC=bbad,DC=lan
2. MsgBox: System.Object[]

etc.

There are much more MsgBoxes but every box is like this.

After looking in our active directory I couldn't figure out the order the entries gets displayed. And I noticed that nothing like "Computer" (see the image) shows up.

Conclusion: I just want to get the computers in bbad.lan > Computer > Standard but the results of my code confuse me so I'm quite perplexed now.

Suggestion appreciated :)

like image 321
roemel Avatar asked Aug 12 '14 10:08

roemel


1 Answers

Try the following using the computer principal class:

        try
        {
            PrincipalContext ctx = new PrincipalContext (ContextType.Domain, "ADDomain", "OU=Standard,OU=Computer,DC=bbad,DC=lan");
            PrincipalSearcher searcher  = new PrincipalSearcher(new ComputerPrincipal(ctx));

            foreach (ComputerPrincipal compPrincipal  in searcher.FindAll())
            {
                //DO your logic
            } 


        }
        catch (Exception ex)
        {
            throw;
        }
like image 145
Bayeni Avatar answered Oct 24 '22 20:10

Bayeni