0
votes

I am trying to setup code to create a new OU (Organizational Unit) in active directory.

The goal is to replicate the security structure from our SSO in Active Directory and automate user provisioning.

I have working code that can create groups and users using PrincipalContext.

The domain controller I am connecting to is in a different domain because its a test computer. I have my computer setup to use this test controller for DNS and have an entry in the host file.

When I run the code below, I get no errors. But whenever I check active directory there is no evidence that the OU was created.

public static void CreateOU()
{
    DirectoryEntry domain = new DirectoryEntry("LDAP://testdomain.test.com/DC=test,DC=com", "username", "password");
    domain.Children.Add("AnotherOU", "OrganizationalUnit");
    domain.CommitChanges();
}

If I put in an invalid ldap path or remove the testdomain.test.com I definately get either login errors (connecting to wrong domain) or other errors with finding the OU.

Edit - The account being used is a domain admin.

Edit - To add to the answer below. I also had to change the AnotherOU name to be OU=AnotherOU otherwise you get a naming violation error.

1
What about the permissions of the account used in the DirectoryEntry's constructor?Oscar
The account is a domain admin right now. I can log onto the controller and manually create OU's using Active Directory Users and Computers.VaultBoy14

1 Answers

2
votes

Try with this:

public static void CreateOU()
{
   DirectoryEntry domain = new DirectoryEntry("LDAP://testdomain.test.com/DC=test,DC=com", "username", "password");
   DirectoryEntry newOU = domain.Children.Add("AnotherOU", "OrganizationalUnit");
   newOU.CommitChanges();
}

You must call CommitChanges() on the newly created object, not in the parent.