【C#代码】使用C#为AD添加用户

开发原因:

测试为什么在真是环境中取数据慢的问题。结论:绝对不是数据量的事情,可能是AD服务器不在本地的原因。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices.AccountManagement;

namespace ADADD
{
    class Program
    {
        private static string stringDomainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
        static void Main(string[] args)
        {
            
            for (int i = 0; i < 10000; i++)
            {
                bool b = CreateUser("wang", "yang", "yixiaozi"+i.ToString(), "00"+i.ToString(), "@foxmail.com", "1232313", "beijing,chaoyang");
            }
        }

        internal static bool CreateUser(string firstName, string lastName, string userLogonName, string employeeID, string emailAddress, string telephone, string address)
        {
            PrincipalContext PrincipalContext1 = new PrincipalContext(ContextType.Domain, stringDomainName);

            UserPrincipal usr = UserPrincipal.FindByIdentity(PrincipalContext1, userLogonName);
            if (usr != null)
            {
                return false;
            }

            // Create the new UserPrincipal object
            UserPrincipal userPrincipal = new UserPrincipal(PrincipalContext1);

            if (lastName != null && lastName.Length > 0)
                userPrincipal.Surname = lastName;

            if (firstName != null && firstName.Length > 0)
                userPrincipal.GivenName = firstName;

            if (employeeID != null && employeeID.Length > 0)
                userPrincipal.EmployeeId = employeeID;

            if (emailAddress != null && emailAddress.Length > 0)
                userPrincipal.EmailAddress = emailAddress;

            if (telephone != null && telephone.Length > 0)
                userPrincipal.VoiceTelephoneNumber = telephone;

            if (userLogonName != null && userLogonName.Length > 0)
                userPrincipal.SamAccountName = userLogonName;

            userPrincipal.SetPassword("a");

            userPrincipal.Enabled = true;
            userPrincipal.ExpirePasswordNow();

            try
            {
                userPrincipal.Save();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }


    }
}

如果不愿意编译,可以直接下载执行文件,不过测试完后删除的代码就需要自己写喽。

http://files.cnblogs.com/files/yixiaozi/ADADD.zip

转载于:https://www.cnblogs.com/yixiaozi/p/4503719.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值