AD: use C # To create accounts in batches

Source: Internet
Author: User
Tags compact time zones email account samaccountname
If a company intends to use Microsoft products to build its own office automation system, it is recommended to use the primary domain control method. Then, the Active Directory (AD) is necessary. In this way, the IT department needs to create a domain account for every employee of the company. If the company is large, this is a huge project. In addition, we will find that some work is basically repetitive, and the human resources department will input various personnel information once to provide a list of personnel for the It department, for example, the name, employee ID, department, department leader, and phone number. After receiving the form, the IT staff will reenter IT again. In addition, account errors are often caused by human reasons. Next, we use C # To compile a program for creating accounts. In this program, it not only creates a domain account, but also creates an email account in the corresponding Exchange. Through this program, the human resources department only needs to fill in related projects according to the database format (Access) provided by the IT department.
First, we need to define some variables:
String strMemberof = "";
String strUserParm = "";
String strManager = "";
String strScriptPath = "";
String strdepartment = "";
String strCompany = "";
// String strAccountExp;
String defaultNC = "DC = Test, DC = net"; // This is the default domain
String alias = "";
String fullName = "";
String password = @ "PassWord"; // This is the default initial password.
String domainName = "test.net ";
String strGivenName = "";

// The following Variable tells the program in which region the mailbox is created in Exchange.
String homeMDB = "CN = Test, CN = holding company ,"
+ "CN = InformationStore, CN = MAIL, CN = Servers ,"
+ "CN = First Administrative Group, CN = Administrative Groups ,"
+ "CN = test, CN = Microsoft Exchange, CN = Services ,"
+ "CN = Configuration, DC = Test, DC = net ";

Label1.Text = "start to load data from the template! ";
// Obtain template information

We know that many projects are the same in a batch of accounts, so we should first create an account as a template, and then, read the data of this template as the data of the corresponding project of the newly created account.
This Code uses the Ad query object:
DirectoryEntry deMb = new DirectoryEntry ();
DeMb. Path = "LDAP: // CN = template, OU = project team, OU = Department, DC = Test, DC = net ";
StrMemberof = deMb. Properties ["memberof"] [0]. ToString ();
StrUserParm = deMb. Properties ["UserParameters"] [0]. ToString ();
StrManager = deMb. Properties ["manager"] [0]. ToString ();
StrScriptPath = deMb. Properties ["scriptPath"] [0]. ToString ();
Strdepartment = deMb. Properties ["department"] [0]. ToString ();
StrCompany = deMb. Properties ["company"] [0]. ToString ();
// StrAccountExp = deMb. Properties ["accountExpires"]. Value. ToString ();
DeMb. Close ();
Label1.Text = "data loaded! Start reading new account information from the database! ";
// Read the database to obtain account information
ADODB. Connection objConn;
ADODB. Command objCmd;
ADODB. Recordset objRs;
Object objOptParm;
ObjOptParm = "";
String str = @ "Jet OLEDB: Global Partial Bulk Ops = 2; Jet OLEDB: Registry Path =; Jet OLEDB: Database Locking Mode = 1; Data Source =" "db1.mdb ""; mode = Share Deny None; Jet OLEDB: Engine Type = 5; Provider = "" Microsoft. jet. OLEDB.4.0 ""; Jet OLEDB: System database =; Jet OLEDB: SFP = False; persist security info = False; Extended Properties =; Jet OLEDB: Compact Without Replica Repair = False; jet OLEDB: Encrypt Database = False; Jet OLEDB: Create System Database = False; Jet OLEDB: Don't Copy Locale on Compact = False; User ID = Admin; Jet OLEDB: global Bulk Transactions = 1 ";
ObjConn = new ADODB. Connection ();
Try
{
ObjConn. Open (str, "", "",-1 );

}
Catch (SystemException ex)
{
MessageBox. Show (ex. Message );

}
Finally
{
//
}
ObjRs = new ADODB. Recordset ();
ObjCmd = new ADODB. Command ();
ObjCmd. CommandText = "select * from sheet1 ";
ObjCmd. ActiveConnection = objConn;
Try
{
ObjRs = objCmd. Execute (out objOptParm, ref objOptParm, 1 );
}
Catch (SystemException ex)
{
ObjConn. Close ();
MessageBox. Show (ex. Message );

}
Finally
{
//
}
Try
{

// Start creating an account
// MessageBox. Show (objRs. Fields [2]. Value. ToString ());
DirectoryEntry container, user;
CDOEXM. IMailboxStore mailbox;
Container = new DirectoryEntry ("LDAP: // OU = project team, OU = Department," + defaultNC );
// Read data
While (! ObjRs. EOF)
{
// Read data
FullName = objRs. Fields [1]. Value. ToString ();
Alias = objRs. Fields [4]. Value. ToString ();
StrGivenName = objRs. Fields [2]. Value. ToString ();
Label1.Text = "create account:" + fullName + "-" + alias + "-" + strGivenName + "check for duplicate accounts! ";
// Check whether there are duplicate accounts
DirectoryEntry su = new DirectoryEntry ("LDAP: // DC = Test, DC = net ");
DirectorySearcher searcher = new DirectorySearcher ();
Searcher. SearchRoot = su;
Searcher. Filter = "(& (objectClass = user) (sAMAccountName =" + alias + "))";
Searcher. SearchScope = SearchScope. Subtree;
Searcher. Sort = new SortOption ("givenName", SortDirection. Ascending );
SearchResultCollection results = searcher. FindAll ();
If (results. Count> 0)
{
// Indicates that there are duplicate accounts. Modify fullname and alias
FullName = fullName + strGivenName;
Alias = alias + strGivenName;

}
// Else
//{
// Create an account
Label1.Text = "create account:" + fullName + "-" + alias + "-" + strGivenName;
Try
{

User = container. Children. Add ("cn =" + fullName, "user ");
User. Properties ["sAMAccountName"]. Add (alias); // account
User. Properties ["userPrincipalName"]. Add (alias + "@ Test.net "));
User. Properties ["givenName"]. Add (strGivenName); // employee ID
User. Properties ["sn"]. Add (fullName); // surname
// User. Properties ["telephoneNumber"]. Add ("0000"); // call
// User. Properties ["mobile"]. Add ("00000000000"); // mobile phone
User. Properties ["company"]. Add (strCompany); // company
User. Properties ["department"]. Add (strdepartment); // department
// User. Properties ["physicalDeliveryOfficeName"]. Add ("0000 ");

// Here, we need to set the Account expiration time, because, according to our regulations, if the account fails to pass the examination before it expires, the account will be disabled. However, this field in AD is an integer and I don't know how to convert it, so I have the following code. I hope you can give me some advice.
DateTime dt = new DateTime (, 0 );
Long longAE = dt. Ticks;
LongAE = longAE-504910656000000000; // minus 8 time zones
User. Properties ["accountExpires"]. Add (longAE. ToString (); // account expiration time

User. Properties ["msNPAllowDialin"]. Value = false; // do not dial in.
User. Properties ["userParameters"]. Add (strUserParm); // disable Terminal Services.

User. Properties ["scriptPath"]. Add (strScriptPath); // configuration file

User. Properties ["manager"]. Add (strManager); // lead
User. Properties ["userPassword"]. Add (password );

// User. Invoke ("SetPassword", new object [] {password });
User. CommitChanges ();
User. Invoke ("SetPassword", new object [] {password });
User. CommitChanges ();
// This enables the new user.
User. Properties ["userAccountControl"]. Value = 0x200; // ADS_UF_NORMAL_ACCOUNT
User. CommitChanges ();

// Obtain the IMailboxStore interface, create the mailbox, and commit the changes.
Mailbox = (IMailboxStore) user. NativeObject;
Mailbox. CreateMailbox (homeMDB );
User. CommitChanges ();

}
Catch (Exception ex)
{
MessageBox. Show (ex. Message. ToString ());
}

//}

Label1.Text = "create account:" + fullName + "-" + alias + "-" + strGivenName + "created! ";
ObjRs. MoveNext ();
}
}
Catch (SystemException ex)
{
ObjConn. Close ();
MessageBox. Show (ex. Message );
}
Finally
{
ObjRs. Close ();
ObjConn. Close ();
MessageBox. Show ("OK ");
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.