Search code examples
c#ldapdirectoryentry

Create OU in active directory for different domain


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.


Solution

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