views:

149

answers:

1

This should be really easy but for some reason it doesn't seem to be. I want to ask AD if the current machine is a member of a particular group. Direct membership is fine.

Group only contains 8 PC's and is extremely unlikely to grow beyond 30.

C# code examples appreciated!

+2  A: 

Here's an example method using the System.DirectoryServices namespace:

public bool BelongsToGroup(string computerName, string groupName, string domain)
{
   PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);

   ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(domainContext, computerName);

   foreach (Principal result in computer.GetGroups())
   {
      if (result.Name == groupName)
      {
         return true;
      }
   }

  return false;
}

So you could call it like this:

string computerName = Environment.MachineName;
string groupName = "Group Name";
string domainName = "Domain Name";
bool test = BelongsToGroup(computerName, groupName, domainName);
Donut
Thanks soooo much! I have just spent 2 hours crying at LDAP error messages!!
Noel Kennedy