PowerCli Script: Migrate host from missing dvSwitch to new dvSwitch with same Id’s

The purpose of this script is to migrate from one vCenter to another when using dvSwitches. The dvSwitch is bound to vCenter, so in order to migrate hosts from one vCenter to another you can map the networks using this script. All you need to do is disconnect the host from the original vCenter with the VMs still running, but not remove it. Then you connect it to the new vCenter.

Requirements:

To use this script it is assumed that you know powershell and have PowerCLI installed. The old and new dvSwitch need to have the same Id and the portgroups need to have the same Id’s. This can be accomplished by doing a backup of your dvSwitch and restoring it in the new vCenter.

You also need a fully configured host in the new vCenter that is connected to the new dvSwitch, this will be the destination host for the migrations.

Import-Module VMware.PowerCLI

$global:DefaultVIServers | Disconnect-VIServer -Confirm:$false

$srcVc = "<fqdn of source vCenter>"
$dstVc = "<fqdn of destination vCenter>"

Connect-VIServer $srcVc
Connect-VIServer $dstVc




$srcHostName = "<fqdn of source host connect to vCenter with old dvSwitch>"
$dstHostName = "<fqdn of destination host connect to vCenter with new dvSwitch>"

$srcHost = Get-VMHost -Server $dstVc $srcHostName
$dstHost = Get-VMHost -Server $dstVc $dstHostName

$dvSwitch = $dstHost | Get-VDSwitch

$VMs = $srcHost | Get-VM

$x = 0
$max = $VMs.Count
foreach ($vm in $VMs) {
    $x += 1
    $nics = $vm | Get-NetworkAdapter
    $PGs = @()
    foreach ($nic in $nics) {
        $PGs += $dvSwitch | Get-VDPortgroup | Where-Object { $_.ExtensionData.Key -eq $nic.ExtensionData.Backing.Port.PortgroupKey }
        if ($PGs.Count -le 0) {
            $nics
            $PGs
            throw "Error, no network found for VM: $vm"
        }
    }
    $i = 0
    foreach ($nic in $nics) {
        Write-Host "($($x)/$($max)) VM: $vm - $($nic.name) - $($nic.NetworkName) - $($PGs[$i].ExtensionData.Key) - $($PGs[$i].Name)"
        $i += 1
    }
    $null = Move-VM $vm -Destination $dstHost -NetworkAdapter $nics -PortGroup $PGs -ErrorAction:Stop
}

IMPORTANT: As alway used this with caution at your own risk. You really need to be familiar with this process. Otherwise you might want to start by doing in manually until your index finger starts bleeding.

View Comments (1)

  • In the script above was this section a mistake?
    $srcHost = Get-VMHost -Server $dstVc $srcHostName
    $dstHost = Get-VMHost -Server $dstVc $dstHostName

    Should it be?
    $srcHost = Get-VMHost -Server $srcVc $srcHostName
    $dstHost = Get-VMHost -Server $dstVc $dstHostName

Related Post