Tuesday, October 20, 2015

Export/Import OU's from Active Directory to LAB

This is a quick and dirty but works.


Here is a simple script to export and then import the OU structure from one AD to another, such as when you want to create a lab from a production AD.


To export the Prod OU's to a CSV, enter the following command:


 Get-ADOrganizationalUnit -Filter *|select name,@{n="Path";E={($_.DistinguishedName).replace("OU="+$_.name+",","") }} | ConvertTo-Csv -NoTypeInformation |out-file -FilePath Prod-OUS-4-Import.csv


Next,  edit the domain name in the CSV to change it to the new domain.
Also, clean up the file to remove any OU's that are out of scope. 


Third, run the following script using the CSV to import the names and Path of the OU's

# Command Line Parameters
Param(
 [Parameter(Mandatory=$false,HelpMessage='CSV FIle')][string]$Inputfile=".\Prod-OUS-4-Import.csv"
)

import-module activedirectory
# Read in data
$OUS = import-csv $InputFile
$ous |ft -a  #validate data on screen

# get current OUs for errorchecking
$currentous = get-adorganizationalunit -filter *

# Create ou for each line in CSV
foreach ($ou in $ous) {
 $error.clear()
 $path = "OU=$($ou.name),$($ou.path)"
 #write-host "$path"
 If ( $currentOUS | ?{$_.DistinguishedName -eq $path } ) {
  write-host  "Exists:  OU=$($ou.name),$($ou.path) already exists" -foregroundcolor yellow
 } else {
  new-ADOrganizationalUnit -name $ou.name -path $ou.path  -ProtectedFromAccidentalDeletion:$false  -ErrorAction:silentlycontinue
  if ($error.count -gt 0) {
   write-host "Failed:  OU=$($ou.name),$($ou.path)"  -foregroundcolor red
  } else {
   write-host "Created: OU=$($ou.name),$($ou.path)"  -foregroundcolor green
  }
 }
}




No comments: