Creating Active Directory computer objects with C#

Creating computer objects in Active Directory with C# does not sound very complex as there are many examples available…

The following code will create a computer in AD:

//BAD Example, do not use it !!!
//get the container for the computer
DirectoryEntry deContainer = new DirectoryEntry("LDAP://CN=Computers,DC=wp01,DC=lab");

//create a computer object
DirectoryEntry deComputer = deContainer.Children.Add("CN=myComputer", "computer");
deComputer.CommitChanges();

but if you check the computer object, you will realize that the Primary Group of the computer is set to "Domain Users" (not good !!):
alt

also the sAMAccountType indicates that the object is a NORMAL_USER_ACCOUNT
alt

Solution:

To get a "valid" computer object, you have to set the attribute userAccountControl to 0x1020 = (PASSWD_NOTREQD | WORKSTATION_TRUST_ACCOUNT) and it's also recommended to set the sAMAccountName to the computername (in uppercase) followed by a '$' (same as if you create the object from the Management Console).

//Get the Container for the Computer
DirectoryEntry deContainer = new DirectoryEntry("LDAP://CN=Computers,DC=wp01,DC=lab");

//Create a computer object
string Computername = "myComputer";
DirectoryEntry deComputer = deContainer.Children.Add("CN=" + Computername, "computer");
deComputer.Properties["sAMAccountName"].Value = Computername.ToUpper() + "$";
deComputer.Properties["userAccountControl"].Value = 0x1020;
deComputer.CommitChanges();

Here we are, the primaryGroupID, sAMAccountType and sAMAccountName is set to the correct value:
alt

.. it's not rocket science, but important to make it the right way...