Active Directory: Copy OU hierarchy from one OU to another OU

Scenario: You want to copy the Sub OU structure/hierarchy from one Parent OU to another Parent OU.

Scriptlet:

#Create OU's
 #Import Module
 import-module activedirectory 
 
#Variables
 $sourceOU = "OU=Old,DC=Domain,DC=com"  
 $destinationOU = "OU=New,DC=Domain,DC=com"  
 $adPath= "LDAP://" + $destinationOU  
 $objDomain=New-Object System.DirectoryServices.DirectoryEntry($adPath)  
 $ObjSearch=New-Object System.DirectoryServices.DirectorySearcher($ObjDomain)  
 [array] $OUs = @() 
 
 #Query for OUs and Exclude an OU if needed
 $OUs = Get-ADOrganizationalUnit -SearchBase $sourceOU -filter * | Where Distinguishedname -notlike "Service" | Select -ExpandProperty DistinguishedName | Sort {$_.length}
 

 #Loop to build the OU Structure
 for ($k=0; $k -le $OUs.Count -1; $k++) 
 { 
     $OriginalOU = $OUs[$k]
     $OriginalOU = "AD:\"+$OriginalOU
    $OUtoCreate = ($OUs[$k] -replace $sourceOU,$destinationOU).ToString()  
     $OUSearch = ($OUtoCreate -replace '"',"").ToString()  
    $ObjSearch.Filter = "(&(objectCategory=organizationalUnit)(distinguishedName="+ $OUSearch + "))"  
    $allSearchResult = $ObjSearch.FindAll()  

    $FinalOU = "AD:\"+$OUtoCreate 

    if ($allSearchResult.Count -eq 1)  
   {      
       "No changes were done on = " + $OUtoCreate  
    }  
    else
    {
      dsadd ou $OUtoCreate
      "OU Creation = " + $OUtoCreate  
    } 
 } 
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: