Can across situation where I needed to move VM from one Vcenter to another.
The following script will do the following:
Will prompt for a Source and Target Vcenter and then ask for user credentials.
Connect to the Source and Target Vcenter. When then cycle through VMs listed from csv file (VMList.csv). (Place the csv file in same directory as the script.)
The list of VMs in the One by one and Migrate the VM to new VC. If the VMs powered on will attempt to shutdown the Server (if VMtools installed) and t
The format of the VMList.csv file needs to be in format as below.
#ensure that not connected to any vCenters
Disconnect-VIServer -Server * -Force -Confirm:$false
#enter Vcenter
Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope User -Confirm:$false
$vc1 = Read-Host "Enter Source Vcenter"
$vc2 = Read-Host "Enter Target Vcenter"
Write-Host "VC1 = " $vc1
Write-Host "VC2 = " $vc2
$vmlist = Import-CSV “$pwd\VMList.csv”
# Connect To Vcenter Server
$User = Read-Host -Prompt "Please enter your VC admin username"
$PW = Read-Host -Prompt "Please enter your VC admin password" -asSecureString
$PW = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($PW))
Connect-VIServer $vc1 -User $User -Password $PW -ErrorAction SilentlyContinue
Connect-VIServer $vc2 -User $User -Password $PW -ErrorAction SilentlyContinue
foreach ($item in $vmlist) {
# Map variables
$vm = $item.vmName
$destESXi = $item.targetesxihost
$destDatastore = $item.targetdatastore
$destVDSwitch = $item.targetDVSwtich
$destPortgroup= $item.targetPortGroup
$typeDisk = $item.Disktype
$vm = get-vm $vm
#Check to see if VM powered off if powered on will shutdown and check ever 5 sec til shutdown
if ($vm.powerstate -eq "PowerdOn"){
write-host "Shutting down" $vm
$vm | Shutdown-VMguest -Confirm:$false
do {
#wait 5 secs
start-Sleep -s 5
$vm = get-vm $vm
$status = $vm.powerstate
}until($status -eq "PoweredOff")
}
Write-Host "===== Connected vCenters ====="
$global:DefaultVIServers | ft -AutoSize
#Command to migrate the VM to new Host in new Vcenter
Write-Host "Moving VM" $vm
Move-VM -VM (Get-VM -Server $vc1 -Name $vm) -VMotionPriority High `
-Destination (Get-VMHost -Server $vc2 -Name $destESXi) `
-Datastore (Get-Datastore -Server $vc2 -Name $destDatastore) -DiskStorageFormat $typeDisk `
-PortGroup (Get-VDPortgroup -Server $vc2 -VDSwitch $destVDSwitch -Name $destPortgroup)
} #end of ForLoop
Disconnect-VIServer -Server * -Force -Confirm:$false