20

Creating Active Directory computer objects with C#

 3 years ago
source link: https://rzander.azurewebsites.net/creating-active-directory-computer-objects-with-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Creating Active Directory computer objects with C#

Roger Zander

6 May 2018 • 1 min read

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...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK