Recursive OU creation with Powershell

In basic AD Powershell, when creating Organizational Units (OU), you are often referred to the New-ADOrganizationalUnit cmdlet, which is fine if you must create one OU or multiple unrelated OUs, but recursive OU creation with Powershell can be verbose.

If you must create multiple OUs which are child, child of child, the cmdlet becomes unpractical: you must concatenate strings to create the DN path or copy/paste them.

A little unknown gem is the powershell ‘AD:’ drive, which allows to traverse the Active Directory structure like a file system. Creating OUs just then become a matter of cd and mkdir commands.

The only gotcha you must be aware is that the name of the object you create must start with the object type. For an OU, it is ‘OU=’. For a container it would be ‘CN=’. In fact, you are using RDN (Relative Distinguished Names) in each folder.

Therefore, at the top of the drive, to enter the domain, you would type in ‘cd .\dc=mydomain,dc=local’ if your domain is mydomain.local

Here is an example:

Adding nested Organizational Units can be then done as:

You can of course use Import-CSV and related cmdlets to import the list of objects that you want to create.

Alternatively you may also use XML format to import an ordered nested structure.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.