当前位置:   article > 正文

批量导入域用户_域用户批量导入

域用户批量导入
  1. private void AddADUser(Workbook workbook)
  2. {
  3. try
  4. {
  5. // 使用PrincipalContext来进行身份验证
  6. using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
  7. {
  8. Worksheet sheet = workbook.Worksheets["用户信息"];
  9. int rowCount = sheet.Rows.Length;
  10. if (rowCount < 2)
  11. {
  12. textBox1.Text += "EXCEL的用户页为空。\r\n";
  13. return;
  14. }
  15. for (int row = 2; row <= rowCount; row++) // Assuming the first row is for headers
  16. {
  17. string firstNm = sheet.Range[row, 1].Value.Trim(); //姓
  18. string sndNm = sheet.Range[row, 2].Value;//名
  19. string acountNm = sheet.Range[row, 3].Value;//acountNm
  20. string password = sheet.Range[row, 4].Value;//密码
  21. string OU = sheet.Range[row, 5].Value;//OU
  22. if (string.IsNullOrEmpty(firstNm) || string.IsNullOrEmpty(acountNm) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(OU))
  23. {
  24. textBox1.Text += "请检查第 " + row + "行是否有空值\r\n";
  25. }
  26. else
  27. {
  28. string userName = acountNm;
  29. if (UserExists(context, userName))
  30. {
  31. textBox1.Text += "用户已存在:" + userName + "\r\n";
  32. }
  33. else
  34. {
  35. // 新建用户
  36. string orgPath = "LDAP://" + OU + ",DC=****,DC=net,DC=cn";
  37. DirectoryEntry ou = new DirectoryEntry(orgPath);
  38. DirectoryEntry newUser = ou.Children.Add("CN=" + firstNm + sndNm, "user");
  39. newUser.Properties["samAccountName"].Value = acountNm;
  40. newUser.Properties["sn"].Value = firstNm;//姓https://www.cnblogs.com/CSharpDevelopers/p/3634635.html
  41. if (!String.IsNullOrEmpty(sndNm))
  42. {
  43. newUser.Properties["givenName"].Value = sndNm;
  44. }
  45. newUser.Properties["userPrincipalName"].Value = acountNm + "@****.net.cn";//用户登录名
  46. newUser.Properties["name"].Value = firstNm + sndNm;
  47. newUser.CommitChanges();
  48. // 设置密码
  49. try
  50. {
  51. Object[] newPassword = new Object[] { password };
  52. newUser.Invoke("SetPassword", newPassword);
  53. newUser.Properties["userAccountControl"].Value = 0x200; // 设置用户为启用状态
  54. newUser.CommitChanges();
  55. textBox1.Text += "已创建用户:" + acountNm + "\r\n";
  56. }
  57. catch (Exception ex)
  58. {
  59. // 处理设置密码时的异常
  60. textBox1.Text += "创建用户失败:" + ex.Message + "\r\n";
  61. }
  62. }
  63. }
  64. }
  65. }
  66. }
  67. catch (Exception ex)
  68. {
  69. textBox1.Text += "添加域用户失败,可能的原因是:" + ex.Message;
  70. }
  71. }
  72. private bool UserExists(PrincipalContext context, string userName)
  73. {
  74. UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
  75. return user != null;
  76. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/905769
推荐阅读
相关标签
  

闽ICP备14008679号