【问题标题】:Add computer principal to group将计算机主体添加到组
【发布时间】:2015-06-22 15:38:28
【问题描述】:

我可以使用命令行中的“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() 处失败,并显示“访问被拒绝”。我在这里错过了什么?

【问题讨论】:

  • 先试试显而易见的:你是如何运行这段 C# 代码的?例如,如果通过 cmd,您是否以管理员身份运行它?如果只是按 F5,VS 是否以足够的权限运行?
  • 冒充用户是否会不关心以提升的权限运行?

标签: c# active-directory console-application active-directory-group


【解决方案1】:

这里有一些问题。您需要将凭据传递给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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多