创建域用户并添加到本地组失败

Posted

技术标签:

【中文标题】创建域用户并添加到本地组失败【英文标题】:Create Domain User and add to local groups failures 【发布时间】:2012-11-29 14:53:26 【问题描述】:

我正在尝试创建域用户,然后将它们添加到当前机器上的本地组中。每次我在域上调用 add 时都这样做,我得到这个"A member could not be added to or removed from the local group because the member does not exist.\r\n"。但是我知道用户存在,因为我的测试人员正在查看目录,并且一旦我的创建代码运行,用户就出现了。

我会说我注意到当我将 SID 转换为 NTUser 帐户时,我最终以 domain\$DDDDD-FAF234AFS 作为名称而不是 domain\test.user。为什么会这样,这可能是我的问题吗?

这是我创建用户的代码:

private UserPrincipal CreateNewUser(Section.User.User user, PrincipalContext principal)
    
        _logger.Debug("User did not exist creating now.");
        UserPrincipal newUser = new UserPrincipal(principal)
            
                Name = user.UserName.Contains('\\') ? user.UserName.Split('\\')[1] : user.UserName,
                Description = string.IsNullOrEmpty(user.UserDescription) ? "IIS 0 user.".FormatWith(user.UserType) : user.UserDescription,
                UserCannotChangePassword = false,
                PasswordNeverExpires = true,
                PasswordNotRequired = false,
                Enabled = true
            ;
        _logger.Debug("User created.");

        _logger.Debug("Setting user password and applying to the system.");
        newUser.SetPassword(user.UserPassword);
        newUser.Save();

        return newUser;
    

用户只是一个带有用户名、密码和描述的自定义类。 principalcontext 是域的有效上下文。

这是我用来将用户添加到本地域的代码:

private void AddDomainUserToGroup(Principal groupPrincipal, Principal user, string group)
    
        using (DirectoryEntry groupEntry = groupPrincipal.GetUnderlyingObject() as DirectoryEntry)
        using (DirectoryEntry userEntry = user.GetUnderlyingObject() as DirectoryEntry)
        
            NTAccount ntUser = user.Sid.Translate(typeof (NTAccount)) as NTAccount;
            string domain = ntUser.ToString().Split('\\')[0];
            string userPath = string.Format("WinNT://0/1,user", domain, user);

            groupEntry.Invoke("Add", new object[] userPath);
        
    

此外,我从未将用户添加到本地计算机,我只是将它们添加到域中。这可能是我的问题吗?

【问题讨论】:

【参考方案1】:

我想通了,如果其他人有类似的问题,这是我的解决方案。基本上它失败了,因为一旦我将 samAccountname 设置为我的用户名,我就从未设置过它,一切正常。

【讨论】:

以上是关于创建域用户并添加到本地组失败的主要内容,如果未能解决你的问题,请参考以下文章

将多个域组添加到本地管理员帐户、验证添加和更改输出颜色的批处理文件

对域用户设置为本地管理员权限

加入域时如何将自定义组自动加入到本地管理员组

怎么才能用命令行把域中的Domain users组加入到本地管理员组中

使用命令行将域用户加入到本地管理员组

如何快速更改域用户所拥有的本地计算机的权限