Set ActiveDirectory if machine is a member of a group

It should be very simple, but for some reason it doesn't look like it. I want to ask AD if the current machine is a member of a specific group. Direct membership is ok.

The group only contains 8 PCs and is highly unlikely to grow to 30.

C # code examples appreciated!

+2


source to share


1 answer


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

:

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 can call it like this:

string computerName = Environment.MachineName;
string groupName = "Group Name";
string domainName = "Domain Name";
bool test = BelongsToGroup(computerName, groupName, domainName);

      

+5


source







All Articles