In one of my previous post, we have seen how to recreate OU structure for the purpose of migrating the clients. https://tekcookie.com/create-active-directory-ou/

Now the task is to move some of the users and computers in the old OU to the new one. The only difference among the old and new OU tree is that the root OU name is different.

The below script reads the OU information from the objects and modify the DistinguishedName and move the objects to the respective new OU. The new OU has got only its root name modified, rest all of the tree remain same as old.

Old OU : domainname.local/DepartmentOU/*

New OU : domainname.local/DepartmentOU_new/*

domainname.local
 |_ DepartmentOU                            ------- OLD OU
   |_ SubDepartmentOU1
     |_ SubDepartmentOU1_USB
     |_ SubDepartmentOU1_Floppy
   |_ SubDepartmentOU2
     |_ SubDepartmentOU2_USB
   |_ SubDepartmentOU3
 |_ DepartmentOU_new                        -------- NEW OU
   |_ SubDepartmentOU1
     |_ SubDepartmentOU1_USB
     |_ SubDepartmentOU1_Floppy
   |_ SubDepartmentOU2
     |_ SubDepartmentOU2_USB
   |_ SubDepartmentOU3 
#List of Users
 $Users = Get-Content D:\Test\Movement\Users.txt
#List of Computers
 $Computers = Get-Content D:\Test\Movement\Computers.txt
 foreach($User in $Users)
 {
     $userInfo = Get-ADUser -Identity $User
     $Detected_OU = $userInfo.DistinguishedName.Split(",")[-3].replace("OU=","")
     $targetOU = $userInfo.DistinguishedName.Substring($userInfo.DistinguishedName.IndexOf(',') + 1, $userInfo.DistinguishedName.Length - $userInfo.DistinguishedName.IndexOf(',') - 1)
     $targetOU = $targetOU.Replace($Detected_OU,"$($Detected_new)_10")
 "Moved: " + $userInfo.DistinguishedName Move-ADObject -Identity $userInfo.DistinguishedName -TargetPath $targetOU
 }
 foreach($Computer in $Computers)
 {
     $ComputerInfo = Get-ADComputer -Identity $Computer
     $Detected_OU = $ComputerInfo.DistinguishedName.Split(",")[-3].replace("OU=","")
     $targetOU = $ComputerInfo.DistinguishedName.Substring($ComputerInfo.DistinguishedName.IndexOf(',') + 1, $ComputerInfo.DistinguishedName.Length - $ComputerInfo.DistinguishedName.IndexOf(',') - 1)
     $targetOU = $targetOU.Replace($Detected_OU,"$($Detected_OU)_new")
 "Moved: " + $ComputerInfo.DistinguishedName Move-ADObject -Identity $ComputerInfo.DistinguishedName -TargetPath $targetOU
 }

Thank you for reading my post. Hope this is helpful to you