PowerShell: Change Hyper-V VM VLAN after Live Migration

One of my old Hyper-V hosts has its virtual switch uplink NICs connected to access ports rather than trunk ports. My other hosts all have trunked uplinks, which means that the VMs need to have a VLAN ID specified to connect them onto the correct VLAN.

I’m gradually moving VMs off the old host, but want to minimise downtime and down’t want to do it out of hours. The problem is that as soon as the VM has finished its Live Migration onto the new host, it stops being able to talk to the network, due to the VLAN ID not being set.

So I wrote this script to monitor the new host for the presence of the VM that’s being migrated, and as soon as it sees it, to set the VLAN ID to the correct value.

$HVHost = "RCMHV01"
$VMName = "OldVM01"
$SwitchName = "LAN Switch"
$VlanID = 250

$Finished = $false

Write-Host "Waiting for $VMName to move onto $HVHost"
while($Finished -ne $true){
    $VMs = Get-VM -ComputerName $HVHost
    if($VMs.Name -contains $VMName){
        Write-Host "Migrated, waiting for Status to be OK"
        while((Get-VM -ComputerName $HVHost -Name $VMName).PrimaryOperationalStatus -ne "Ok"){
            Start-Sleep -Seconds 1
        }
        $VM = Get-VM -ComputerName $HVHost -Name $VMName
        $VMNICs = Get-VMNetworkAdapter -VM $VM
        foreach($VMNIC in $VMNICs){
            if($VMNIC.SwitchName -eq $SwitchName){
                Write-Host "Configure VMNIC"
                Set-VMNetworkAdapterVlan -VMNetworkAdapter $VMNIC -VlanId $VlanID -Access
                $Finished = $true
            }
        }

    }
}
This entry was posted in Hyper-V, PowerShell and tagged , , , , , , . Bookmark the permalink.

One Response to PowerShell: Change Hyper-V VM VLAN after Live Migration

  1. Chad says:

    AWESOME! This is exactly what will save us downtime for a slow SAN migration. Thanks for posting this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s