将计算机主体添加到组

Add computer principal to group

我可以使用命令行中的 "net group" 命令将机器名称 "MACHINE1$" 添加到组 "GROUP1"。

但是我无法以编程方式执行相同的操作:

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;
        }

代码在 computerPrincipal.Save() 处失败并出现 "Access is denied"。我在这里错过了什么?

这里有一些错误。您需要将凭据传递给 PrincipalContext 构造函数,并且不需要使用模拟。出于某种原因,您还试图创建一个新的 ComputerContext

试试这个:

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;
    }
}