Add computer principal to group

998 views Asked by At

I am able to add machine name "MACHINE1$" to the group "GROUP1" using "net group" commands from a command line.

However I am not able to do the same programmatically:

public static bool AddToGroup(string machineName, string groupName)
        {
            using (
                new ImpersonateUser("Domain", "ServiceAccountLogonName", "ServiceAccountPassword"))
            {
                var ctx = new PrincipalContext(ContextType.Domain);

                var group = GroupPrincipal.FindByIdentity(ctx, groupName);

                if (@group == null)
                {
                    return false;
                }
                var computerPrincipal = new ComputerPrincipal(ctx) { Name = machineName };
                computerPrincipal.Save();
                @group.Members.Add(computerPrincipal);
                @group.Save();
            }
            return true;
        }

The code fails at computerPrincipal.Save() with "Access is denied". What am I missing here?

1

There are 1 answers

0
Ashigore On BEST ANSWER

There are a few things wrong here. You need to pass the credentials to the PrincipalContext constructor and you do not need to use impersonation. You are also trying to create a new ComputerContext for some reason.

Try this:

public static bool AddToGroup(string computerName, string groupName)
{
    using (var context = new PrincipalContext(ContextType.Domain, "Domain", "ServiceAccountLogonName", "ServiceAccountPassword"))
    using (var group = GroupPrincipal.FindByIdentity(context, groupName))
    using (var computer = ComputerPrincipal.FindByIdentity(context, computerName)
    {
        if (group == null || computer == null)
        {
            return false;
        }
        group.Members.Add(computer);
        group.Save();
        return true;
    }
}