Powershell Script to Replicate OU Structure from Source OU to Target OU.

Powershell Script to Replicate OU Structure from Source OU to Target OU.


Purpose of the Script: i wrote the script to replicate the OU & Sub OU Structure from one OU to Another OU, the below script will take a backup of Source and Target OU before and after replication to CSV file.
Note: test it in test OU's before running in Prod OUs, it worked like charming.
Post comments for improvements.


Script:
import-module activedirectory
####Current OU Structure in Source & target for reference#####
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU1,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./BeforeSourceOUReplication.csv
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU2,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./BeforeTargetOUReplication.csv
##################
$sourceOU = "<OU Path; ex: OU=TestOU1,DC=XX,DC=XXXXX,DC=com>"
$destinationOU = "<OU Path; ex: OU=TestOU2,DC=XX,DC=XXXXX,DC=com>"
##################
#--------Main
##################
$adPath= "LDAP://" + $destinationOU
#Create OUs
$objDomain=New-Object System.DirectoryServices.DirectoryEntry($adPath)
$ObjSearch=New-Object System.DirectoryServices.DirectorySearcher($ObjDomain)
[array] $OUs = @()
$OUs = dsquery * $sourceOU -Filter "(objectCategory=organizationalUnit)" -limit 0
$OUsorted = $OUs | sort-object { $_.Length}
for ($k=0; $k -le $OUsorted.Count -1; $k++)
{
    $OUtoCreate = ($OUsorted[$k] -replace $sourceOU,$destinationOU).ToString()
    $OUSearch = ($OUtoCreate -replace '"',"").ToString()
    $ObjSearch.Filter = "(&(objectCategory=organizationalUnit)(distinguishedName="+ $OUSearch + "))"
    $allSearchResult = $ObjSearch.FindAll()
    if ($allSearchResult.Count -eq 1)
    {
        "No changes were done on = " + $OUtoCreate
    }
    else
    {
        dsadd ou $OUtoCreate
        "OU Creation = " + $OUtoCreate
    }
}
####OU Structure after replication in Source & target for validation####
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU1,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./AfterSourceOUReplication.csv
Get-ADOrganizationalUnit -Filter * -SearchBase "<OU Path; ex: OU=TestOU2,DC=XX,DC=XXXXX,DC=com>" -Properties canonicalname | select DistinguishedName | export-csv ./AfterTargetOUReplication.csv

No comments:

Post a Comment