Change VM Port Group – changevmportgroup.ps1

You are here:
< Back


#Change VM Port Group - changevmportgroup.ps1
#Erik Hinderer
#ehinderer@vmware.com
#Version 0.3

# Script to migrate all VM vNICs from one portgroup to another
#
# Script takes input (VLAN ID) on the command line and imports a CSV file with candidate VLAN/portgroup information
#
# CSV file: "VLAN","portgroup","wire"
# where "wire" is the ip notation of the network, which is assumed to be the ending string of the virtualwire name
#
# Script is intended to faclitate migrating to/from VXLAN virtual wires
#
# Last modified 8/18/17

$vcenter = "myvcenterFQDN"

$vlan = $args[0]
cls
If (!$vlan) {
  "Please enter a VLAN ID"
} Else { 

  $importportgroups = import-csv c:\scripts\ImportPortGroups.csv
  $portgroup = ($importportgroups | where {$_.VLAN -eq $vlan}).portgroup
  $wire = ($importportgroups | where {$_.VLAN -eq $vlan}).wire

  if (!$defaultviserver) {connect-viserver $vcenter}

  $wirename = get-virtualportgroup |where {$_.name -like "*$($wire)"}

  $pg =   get-virtualportgroup -name $portgroup  

  "`nYou have selected VLAN $($vlan) which maps port group $($pg.name) to virtual wire $($wirename.name)`n" 

  $conf = Read-Host "Is this correct? (Y/N)"
  if ($conf -eq "y") {
    cls  
    "Counting vNICs`n"  
    $vms = get-vm
    $wirevms = $vms| get-networkadapter |where {$_.networkname -eq $wirename.name}
    $pgvms = $vms| get-networkadapter |where {$_.networkname -eq $pg.name}
    "`nThere are $($pgvms.count) VM vNICs on the portgroup and $($wirevms.count) VM vNICs on the virtual wire.`n"
    "Press 1 to move all VMs on the portgroup to the virtual wire.  Press 2 to move all VMs on the virtual wire to the portgroup.`n"
    
    do {  
      $key = Read-Host "Or press C to cancel. [1/2/C]"
    }until ("12C" -match $key)

    if ($key -eq "1") {
      $out = $pgvms | set-networkadapter -networkname $wirename.name -Confirm:$false
    } elseif ($key -eq "2") {
      $out = $wirevms | set-networkadapter -networkname $pg.name -Confirm:$false
    } else {exit }
    "`nMigration completed, recounting vNICs.`n"
    $wirevms = $vms| get-networkadapter |where {$_.networkname -eq $wirename.name}
    $pgvms = $vms| get-networkadapter |where {$_.networkname -eq $pg.name}
    "`nThere are now $($pgvms.count) VM vNICs on the portgroup and $($wirevms.count) VM vNICs on the virtual wire.`n"
}
}