#Powershell to import AD OU Structure from a CSV

So the next step to this post (#Powershell to export AD OU Structure) is to import the OUs.  This is quite simple and uses ADSI to create new OUs.  The CSV need to have atleast a column called Path, and that could be in this format:

“AdministrationGroupsDomain Local Groups”
“AdministrationGroupsGlobal Groups”,

The script will then reverse the path and convert it to a DN and create the OUs.  If the OU exists, the script will error and continue.  Enjoy


$CSVin = Import-Csv c:psOUs.csv
$OUs   = $CSVin | Sort Path

#CSV file need to have atleast a column called Path

$CurrentDomain = [System.DirectoryServices.ActiveDirectory.Domain]::getcurrentdomain()
$DC            = $CurrentDomain.FindDomainController().name + “:389″ #”localhost:389”
$Forest        = $CurrentDomain.Forest.ToString()
$Forest        = “dc=” + $Forest
$Forest        = $Forest.Replace(“.”,”,dc=”)
$domain        = [ADSI]”LDAP://$dc/$Forest”

ForEach($OU in $OUs){
  #Using the OU Path from the CSV File, split it down
  $tmpOU = $OU.Path.Split(“”)

  #Reverse the Path and make it AD happy
  $ActualOU=””;For($i=$tmpOU.Length;$i–;$i -eq 0){IF($tmpOU[$i] -ne “”){$ActualOU+= “OU=” + $tmpOU[$i] + “,”}}

  #Remove the trailing comma
  $ActualOU = $ActualOU.Substring(0, $ActualOU.Length-1)

  #Add the OU.  If it exists it will error but continue
  $NewOU = $Domain.Create(“organizationalunit”, $ActualOU); $NewOU.SetInfo()

Next step is to import users and groups from a CSV .. coming soon.

Leave a Reply

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

%d bloggers like this: