使用LDAP将用户添加到AD

时间:2012-03-21 20:17:40

标签: vb.net active-directory ldap

我正在编写一个将用户添加到Active Directory的应用程序。我正在尝试使用此代码连接到AD

中的“Users”共享文件夹
LDAP://celtestdomdc1.celtestdom.local/CN=Users,DC=celtestdom,DC=local

但是,它会将用户添加到共享文件夹中,而不是“Users”共享文件夹中。不应该CN =用户意味着它会将它添加到“用户”文件夹?

谢谢

1 个答案:

答案 0 :(得分:3)

如果您正在创建用户,则需要

  • 绑定到您要在
  • 中创建用户的容器
  • 将新用户帐户创建为该容器的子级

只需设置LDAP路径,您定义用户的去向!

尝试类似这样的事情(C#sample - 转换为VB.NET应该很简单):

DirectoryEntry cnUsers = new DirectoryEntry("LDAP://CN=Users,DC=celtestdom,DC=local");

// create a user directory entry in the container
DirectoryEntry newUser = container.Children.Add("cn=NewUserAccount", "user");

// add the samAccountName mandatory attribute
newUser.Properties["sAMAccountName"].Value = "NewUser";

// add any optional attributes
newUser.Properties["givenName"].Value = "User";
newUser.Properties["sn"].Value = "One";

// save to the directory
newUser.CommitChanges();

// set a password for the user account
// using Invoke method and IadsUser.SetPassword
newUser.Invoke("SetPassword", new object[] { "pAssw0rdO1" });

// require that the password must be changed on next logon
newUser.Properties["pwdLastSet"].Value = 0;

// save to the directory
newUser.CommitChanges();

或者,如果您使用的是.NET 3.5或更高版本,您还可以使用新的System.DirectoryServices.AccountManagement命名空间,这可以让您轻松完成任务。

然后代码看起来更简单:

// create a context for a domain and define "base" container to use
PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
         "celtestdom", "CN=Users,DC=celtestdom,DC=local");

// create a user principal object
UserPrincipal user = new UserPrincipal(ctx, "NewUser", "pass@1w0rd01", true);

// assign some properties to the user principal
user.GivenName = "User";
user.Surname = "One";

// force the user to change password at next logon
user.ExpirePasswordNow();

// save the user to the directory
user.Save();

在此处查看有关System.DirectoryServices.AccountManagement(S.DS.AM)命名空间的更多信息:

相关问题