Wednesday, September 02, 2009

How to create active directory users programmatically

Recently one of my colleagues wanted a piece of code which can be created 500 users in Active Directory for some testing purposes.Knowing that this won’t be a big challenge I said I will give it a try.

Frankly speaking, initially I thought this will be a easy walk in the park.Creating the user in AD part was a piece of cake but the created user was not enabled by default.

I had to figure out how to enable a user account programmatically.That was the only tricky part.

Check the user enabling code segment in the code.(Setting the "userAccountControl" property of the user)

Here is the code

string ldapPath = "LDAP://" + server + "/cn=Users,dc=ec,dc=test";

DirectoryEntry entry = new DirectoryEntry(ldapPath, user, pwd);

for (int i = 0; i < userCount; i++)
{
string tempName = userPrifix + i;
DirectoryEntry newUser = entry.Children.Add("CN=" + tempName, "user");
newUser.Properties["givenName"].Add(tempName);
newUser.Properties["userPrincipalName"].Add(tempName + "@ec.test");
newUser.Properties["sAMAccountName"].Add(tempName);
newUser.Password = userPwd;

newUser.CommitChanges();

// Enabling the above created account
int flags = (int)newUser.Properties["userAccountControl"].Value;
newUser.Properties["userAccountControl"].Value = flags & ~0x2;

newUser.CommitChanges();

newUser.Close();
entry.Close();
}
References :

http://www.codeproject.com/KB/system/everythingInAD.aspx

http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm

No comments: