Find out how to move computer objects to different OU. In this example, you need to have the Active Directory module installed and distingushednames of the target organizational unit and the source.
Move computers
PowerShell script is based on Move-ADObject command. This cmdlet moves an object or a container of objects from one container to another or from one domain to another.
To move a single computer you can use the following one-liner script:
Move-ADObject -Identity "CN=DC01,OU=TestServers,OU=Administration,DC=PowerShellBros,DC=com" -TargetPath "OU=Servers,OU=Administration,DC=PowerShellBros,DC=com"
Below you can find a script that first gets all computers from specified OU ($ServersOU) that starts with DC and then move all of the computer objects to target OU. Next, results are exported to CSV and displayed at the end in the console.
Try{ #AD Module Import-Module ActiveDirectory -ErrorAction Stop #Properties $FileDate = Get-Date -Format "yyyyMMddHHmmss" $ReportPath = "$env:userprofile\desktop\" $OutputCsv = "$ReportPath\Computers_$FileDate.csv" $ServersOU = "OU=TestServers,OU=Administration,DC=PowerShellBros,DC=com" $TargetOU = "OU=Servers,OU=Administration,DC=PowerShellBros,DC=com" #Get Computers $Params = @{ LDAPFilter = "(name=DC*)" Server = ($env:LOGONSERVER -replace "\\",'') SearchBase = $ServersOU } $Computers = Get-ADComputer @Params #Looping comps and export results to CSV Foreach($Comp in $Computers){ Move-ADObject -Identity $($Comp.Distinguishedname) -TargetPath $TargetOU -PassThru | Export-Csv $OutputCsv -Append -NoTypeInformation } #Results Write-Host "`nResults:" Import-CSV $OutputCsv | Format-Table -AutoSize } Catch{ Write-Warning $_.Exception.Message Read-Host "Script will end. Press enter to close the window" Exit }
I hope this was informative for you 🙂 See you in the next articles.
Hi,
That is a very good script.
I am looking for this same script, but I have a txt file with only the computers’ name.
how can it be modified to search on the source OU for the computer list on the txt file and move them to the other OU?
can you help me?
Thank you