This script demonstrates how to recreate Organizational Unit structure from existing OU’s in AD
Suppose we have the below OU in AD domain
domainname.local |_ DepartmentOU |_ SubDepartmentOU1 |_ SubDepartmentOU1_USB |_ SubDepartmentOU1_Floppy |_ SubDepartmentOU2 |_ SubDepartmentOU2_USB |_ SubDepartmentOU3
DepartmentOU branch need to be duplicated with different name DepartmentOU_new
domainname.local |_ DepartmentOU |_ SubDepartmentOU1 |_ SubDepartmentOU1_USB |_ SubDepartmentOU1_Floppy |_ SubDepartmentOU2 |_ SubDepartmentOU2_USB |_ SubDepartmentOU3 |_ DepartmentOU_new |_ SubDepartmentOU1 |_ SubDepartmentOU1_USB |_ SubDepartmentOU1_Floppy |_ SubDepartmentOU2 |_ SubDepartmentOU2_USB |_ SubDepartmentOU3
It can be done with the below script
$rootOUName = "DepartmentOU_new"
$newRootDN = "OU=DepartmentOU_new,DC=domainname,DC=local"
$oldRootDN = "OU=DepartmentOU,DC=domainname,DC=local"
$rootOU_ParentDN = "DC=domainname,DC=local"
We are reading the canonical name just as a place holder to keep the parent OU of the object
$old_ChildOUs = Get-ADOrganizationalUnit -Filter * -Properties * | where {$_.DistinguishedName -like "*$oldRootDN" -and $_.DistinguishedName -ne "$oldRootDN" }
| select Name, CanonicalName, DistinguishedName, Description
To fetch the description form the existing root ou
$oldRootDN_temp = Get-ADOrganizationalUnit -Filter * -Properties * | where {$_.DistinguishedName -eq "$oldRootDN" }
| select Name, DistinguishedName, Description
For each sub OU, the root has to be renamed to the desired name and base path has to be made
$count = 0
foreach($ou in $old_ChildOUs) {
#renaming the OU with new name
$ou.DistinguishedName = $ou.DistinguishedName.Replace($oldRootDN, $newRootDN)
#building the base OU for each child OU #we split the DN with comma "," and rejoin the array from 2nd location to the last and save it into the same objects canonical name property $rootOU = ($ou.DistinguishedName.Split(",")) $rootOU = $rootOU[1..$rootOU.length] -join "," $old_ChildOUs[$count].CanonicalName = $rootOU $old_ChildOUs[$count].DistinguishedName = $ou.DistinguishedName $count++
}
Creating the parent OU
New-ADOrganizationalUnit -Name $rootOUName -Path $rootOU_ParentDN -Description $oldRootDN_temp.Description
"Created parent ou : " + $rootOUName + " under " + $rootOU_ParentDN
creating all child OU's
foreach($__newOU in $old_ChildOUs){
New-ADOrganizationalUnit -Name $__newOU.Name -Path $__newOU.CanonicalName -Description $__newOU.Description
"Created ou : " + $__newOU.Name + " under " + $__newOU.CanonicalName
}
The script will generate the OU structure with default security permission inherited from the root.
Thank you reading my post. Hope this is helpful to you.
Recent Comments