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?
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 newComputerContext
for some reason.Try this: