我们有一个域sfb-ber
,此域中的用户sfb-ber\sfb
,samAccountName
sfb
以及此域中的计算机{{1} },sfb.sfb-ber.local
samAccountName
。我尝试使用以下代码在此计算机上创建本地用户:
sfb$
用户创建成功,但代码打印出以下内容:
var context = new PrincipalContext(ContextType.Machine);
var userPrincipal = new UserPrincipal(context, "testusr", "testpwd", true);
userPrincipal.Save();
var entry = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
Console.WriteLine("{0} {1}", entry.SchemaEntry.Name, entry.Path);
Console.WriteLine("{0} {1}", entry.Parent.SchemaEntry.Name, entry.Parent.Path);
Console.WriteLine("{0} {1}", entry.Parent.Parent.SchemaEntry.Name, entry.Parent.Parent.Path);
用户似乎被创建为现有User WinNT://SFB-BER/SFB/testusr
User WinNT://SFB-BER/SFB
Domain WinNT://SFB-BER
用户的子对象,而不是sfb
计算机。这在稍后尝试以编程方式删除用户时会导致问题。如何在不重命名机器的情况下防止这种情况发生?
编辑最后,我们选择不以编程方式创建用户,但记录此边缘情况并要求系统管理员手动执行此操作。我仍然想知道如何解决这个问题,所以一旦我获得更多代表,我就会分配新的赏金。
答案 0 :(得分:2)
尝试使用域级别上下文而不是计算机:
using(var pc = new PrincipalContext(ContextType.Domain))
{
using(var up = new UserPrincipal(pc))
{
up.SamAccountName = username;
up.EmailAddress = email;
up.SetPassword(password);
up.Enabled = true;
up.ExpirePasswordNow();
up.Save();
}
}