Active Directory 2012

Active Directory – Create OU using Powershell

Sometimes, you need to create a lot of Organization Units into your Active Directory.
To do this, you can use the Active Directory Users and Computers but it can be quickly time consuming depends on the number of OU.

Hopefully, Microsoft integrated a powershell module with Active Directory. So, we can create a script to do this for us.

CSV

The first thing to do is to create, think about information in the file.  In this example, I only used Name and Path, but you can use others parameters like Managed By, Country, Protected,…

  • Name : The name of the new Organization Unit.
  • Path : DN Path of the parent Organization Unit.
name;path
Servers;OU=LAB,DC=LAB,DC=local
Workstations;OU=LAB,DC=LAB,DC=local
Users;OU=LAB,DC=LAB,DC=local
Service Account;OU=LAB,DC=LAB,DC=local

Powershell

In order to create OU automatically from the CSV file, we will use an Active Directory built-in cmdlet: New-ADOrganizationalUnit.

This script is composed of 3 steps:

  • Read CSV File, given in parameter of the script
  • Read each line
  • Call the cmdlet to create OU in Active Directory with information.

In case of error, like user rights or bad parent path, it will display the specific error.

#-------------------------------------------------------------------------
# Author      : Alexandre VIOT alexandreviot.net
# FileName    : New-OU.ps1
# Version     : 1.0
# Revision    :
# Created     : 26.04.15
# Description : Powershell script creates OU into Active Directory from a CSV File.
# Remarks     : CSV file must contains Name and Path.
#
#-------------------------------------------------------------------------
param([parameter(Mandatory=$true)] [String]$FileCSV)
$listOU=Import-CSV $FileCSV -Delimiter ";"
ForEach($OU in $listOU){
 
try{
#Get Name and Path from the source file
$OUName = $OU.Name
$OUPath = $OU.Path
 
#Display the name and path of the new OU
Write-Host -Foregroundcolor Yellow $OUName $OUPath
 
#Create OU
New-ADOrganizationalUnit -Name "$OUName" -Path "$OUPath"
 
#Display confirmation
Write-Host -ForegroundColor Green "OU $OUName created"
}catch{
 
Write-Host $error[0].Exception.Message
}
 
}

You can call the script with:

.\New-OU.ps1 -FileCSV .\listOU.csv

The Output will be:

Active Directory Powershell

Active Directory Powershell – OU Output

Active Directory Users and Computers

If you check the change with ADUC, you will see that all OU in the file had been created.

Active Directory OU

Active Directory OU

More

You could get more information about New-ADOrganizationalUnit cmdlet here.
You also can download the script in the attachment:

Powershell New-OU
Filename : powershell_ou.zip (849 B)
Caption : Powershell New-OU

Share

One thought on “Active Directory – Create OU using Powershell

Leave a Reply

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