最近要给客户做培训需要配置一个测试环境,因为系统使用域用户验证,建立大量的域用户工作量比较大,而且测试环境的用户名可以根据用户单位和角色建立一个用户名模式,例如:角色.单位

于是用c#批量建立用户,发现这样两个比较棘手的问题:
1. 如何设置用户名初始密码
2. 如何设置“用户下次登陆时须更改密码”不选中(缺省选中)

最终的测试建立用户的代码如下:

1 DirectoryEntry AD = new DirectoryEntry("LDAP://dc=cnblogs,dc=com","administrator","pa$$word",AuthenticationTypes.Secure);
  2             DirectorySearcher searcher = new DirectorySearcher(AD);
  3             searcher.Filter = String.Format("ou={0}","Blogs");
  4             SearchResult result = searcher.FindOne();
  5             if(result!=null)
  6             {
  7                 string samAccountName = "tester";
  8                 string displayName = "测试创建";
  9                 DirectoryEntry userEntry = result.GetDirectoryEntry().Children.Add(String.Format("CN={0}",samAccountName),"User");
 10                 userEntry.Properties["sAMAccountName"].Add(samAccountName);
 11                 userEntry.Properties["displayName"].Add(displayName);
 12                 userEntry.Properties["UserPassword"].Add("pa$$word");
 13                 userEntry.Properties["userAccountControl"].Value = 544;
 14                 userEntry.Properties["pwdLastSet"].Value = -1;
 15                 userEntry.CommitChanges();
 16                 userEntry.Invoke("SetPassword",new object[] {"pa$$word"});
 17             }

注意两点:
1. userEntry.Invoke("SetPassword",new object[] {"pa$$word"}); 一定要在userEntry.CommitChanges();之后才能成功调用;
2.userEntry.Properties["pwdLastSet"].Value = -1; 设置“用户下次登陆时须更改密码”不选中,参考一下链接
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/modifying_user_cannot_change_password_ldap_provider.asp