PoshCode Logo PowerShell Code Repository

Set-dvSwitch (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1373"></script>download | new post

More info can be found here: http://ict-freak.nl/2009/10/06/powercli-set-dvswitch/

Set-dvSwitch VirtualMachine dvSwitchPortgroup

  1. Function Set-dvSwitch {
  2.         param($vmName,$dvPG) # the two parameters.
  3.  
  4.         $nic = "Network adapter 1"      # change this line if you want to change network adapter 2
  5.  
  6.         # Find the NIC
  7.         $vm = Get-VM $vmName | Get-View
  8.         foreach($tempdev in $vm.Config.Hardware.Device){
  9.                 if($tempdev.DeviceInfo.Label -eq $nic){
  10.                         $tgtdev = $tempdev
  11.                 }
  12.         }
  13.  
  14.         # Find the dvSwitch & dvPortGroup
  15.         $esx = Get-View -Id $vm.Runtime.Host
  16.         foreach($netMoRef in $esx.Network){
  17.                 if($netMoRef.Type -eq "DistributedVirtualPortGroup"){
  18.                         $net = Get-View -Id $netMoRef
  19.                         if($net.Name -eq $dvPg){
  20.                                 $dvPGKey = $net.MoRef.Value
  21.                                 $dvSwitchUuid = (Get-View -Id $net.Config.DistributedVirtualSwitch).Summary.Uuid
  22.                         }
  23.                 }
  24.         }
  25.  
  26.         # Prepare Spec
  27.         $spec = New-Object VMware.Vim.VirtualMachineConfigSpec
  28.         $devChange = New-Object VMware.Vim.VirtualDeviceConfigSpec
  29.         $devChange.operation = "edit"
  30.  
  31.         $dev = New-Object ("VMware.Vim." + $tgtdev.GetType().Name)
  32.         $dev.deviceInfo = New-Object VMware.Vim.Description
  33.         $dev.deviceInfo.label = $tgtdev.DeviceInfo.Label
  34.         $dev.deviceInfo.summary = $tgtdev.DeviceInfo.Summary
  35.         $dev.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo
  36.         $dev.Backing.Port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection
  37.         $dev.Backing.Port.PortgroupKey = $dvPGKey
  38.         $dev.Backing.Port.SwitchUuid = $dvSwitchUuid
  39.         $dev.Key = $tgtdev.Key
  40.  
  41.         $devChange.Device = $dev
  42.         $spec.deviceChange = $devChange
  43.  
  44.         $taskMoRef = $vm.ReconfigVM_Task($spec)
  45. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me