Techibee.com

Powershell: Move Computer accounts from default container to specific OU

Whenever a computer is added to a windows domain, by default account will get created under Computers container. It is located right below the domain name in dsa.msc. The pull of it is, <domainName>\Computers.

Today one of my friend has asked to know if there any quick script using which he can move all computers from default computers container to OU of his choice in same domain. Since I don’t have a script already authored for this purpose, I quickly made the below.

This is a very basic version of computer accounts movement script. There might be some conditions processing like if name contains XYZ move to one OU or if name contains ABC move to different OU. You can accommodate such conditions in this script if you have little powershell knowledge(or let me know I can help you given some time).

Here is the code.

[cmdletbinding()]            

param (
[parameter(mandatory=$true)]
$TargetOU
)            

Import-Module ActiveDirectory
$Domain = [ADSI]""
$DN=$domain.distinguishedName
$SourcePath = "CN=Computers," + $DN
$Computers = Get-ADComputer -Filter * -SearchBase $SourcePath
if(!$Computers) {
 write-host "No Computers are found in default container"
 return
}
foreach ($Computer in $Computers) {
 if(!(Move-ADObject $Computer -TargetPath $TargetOU)) {
  $Status = "SUCCESS"
 } else {
  $Status = "FAILED"
 }
 $OutputObj = New-Object -TypeName PSobject
 $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.Name.tostring()
 $OutputObj | Add-Member -MemberType NoteProperty -Name SourcePath -Value $SourcePath
 $OutputObj | Add-Member -MemberType NoteProperty -Name DestinationPath -Value $TargetOU
 $OutputObj | Add-Member -MemberType NoteProperty -Name Status -Value $Status
 $OutputObj
}

 

When I executed this script in my test domain for testing purpose it went fine and generated below output. This script is not depending on any external modules/cmdlets like quest tools. I uses ActiveDirectory module which comes with RSAT(or windows 2008 domain controllers). Needless to say that you need ADWS(active directory web services) installed if all your domain controllers are Windows 2003. This is not required if atleast one DC is having windows 2008 R2 OS where ADWS is default.

Output:

Exit mobile version