如何创建没有密码的新用户帐户

How to create new user account without password

我想以编程方式将新的本地用户添加到计算机。我找到了代码 here。 但我希望用户无需密码即可登录。我看到有一个选项 UserPrincipal.PasswordNotRequired=true 但如果我不使用 SetPassword() 它会抛出一个异常:

The password does not meet the password policy requirements...

是否可以创建一个没有密码的新用户?

编辑: 当前代码,成功添加新用户,但我必须提供一些 password.It 是 link 的完整副本提供:

PrincipalContext oPrincipalContext = GetPrincipalContext();

UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext);
oUserPrincipal.Name = sUserName;
oUserPrincipal.SetPassword(sPassword);
oUserPrincipal.DisplayName = windowsUsername.Text;
oUserPrincipal.PasswordNeverExpires = true;
oUserPrincipal.PasswordNotRequired = true;
oUserPrincipal.Save();

GroupPrincipal usersGroup = GroupPrincipal.FindByIdentity(oPrincipalContext, "Users");
usersGroup.Members.Add(oUserPrincipal);
usersGroup.Save();

您的代码无法正常工作有两个可能的原因。

  1. 你不是 运行 管理员
  2. 您的计算机所在的域中的组策略阻止了您的操作。

下面的代码已经在我的机器上测试过,可以正常工作。

void Main()
{
    PrincipalContext oPrincipalContext = GetPrincipalContext();

    UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext);
    oUserPrincipal.Name = "TestUser";
    oUserPrincipal.SetPassword("");
    oUserPrincipal.DisplayName = "TestUser";
    oUserPrincipal.PasswordNeverExpires = true;
    oUserPrincipal.PasswordNotRequired = true;
    oUserPrincipal.Save();

    GroupPrincipal usersGroup = GroupPrincipal.FindByIdentity(oPrincipalContext, "Users");
    usersGroup.Members.Add(oUserPrincipal);
    usersGroup.Save();
}

PrincipalContext GetPrincipalContext()
{
    var dc = new PrincipalContext(ContextType.Machine);
    return dc;
}

你可以尝试的东西, 1. 在不在您域中的机器上尝试。 2. 在没有应用任何组策略的机器上尝试。 3. 运行 你的应用程序在你遇到问题的机器上作为管理员