PowerCLI to set multiple NICs on VM

KapsZ28

2[H]4U
Joined
May 29, 2009
Messages
2,114
I am moving VMs from one vCenter to another. Since we use distributed port groups, the network adapters show up as "invalid backing". For VMs with a single adapter it is easy to update with a script. What I would like to do is update all the network adapters via a script.

I am thinking there could be a couple of different ways. The VMs obviously have Network adapter 1, Network adapter 2, etc. Also the MAC address stays the same. I can't figure out any commands that work by changing the network connection based on MAC. I was able to use the following which is fine for the first adapter.

Code:
get-vm VMCGS01 | Get-NetworkAdapter | select -First 1 | Set-NetworkAdapter -NetworkName Public-Network
That changes just Network adapter 1. I could also use the -Last switch to change the last adapter. But we have VMs with 3 and 4 NICs.

I found an example on VMware's website for modifying an adapter based on MAC, but it doesn't seem to work.

Code:
Get-VM VM | Get-NetworkAdapter | Set-NetworkAdapter -MacAddress '00:50:56:a1:00:00' -WakeOnLan:$true
I figured just change -WakeOnLan to -NetworkName and I would be good, but any combination of the "Set-NetworkAdapter -MacAddress" command throws the error "The MAC address is invalid or is not in the valid range 00:50:56:00:00:00 - 00:50:56:3F:FF:FF." This doesn't really make any sense since the MAC is right.

Any suggestions?
 
I had an issue a while back in ESXi5.0 where I had to fix all the NIC mappings for a ton of VMs, many with multiple NICs. I used the following to do that so you can hopefully use it as a base.

Code:
foreach ($arg in $args)
{
  Write-Host "Fixing: $arg";

  $VMList = Get-VM -Name $arg
  $AdapterList = $VMList | get-networkadapter

  $temp_network = "pxe_net"

  $list = @()
  Foreach ($VM in $VMList)
  {
    Foreach ($adapter in $AdapterList)
    {
        $old_network = Get-NetworkAdapter -VM $VM.name -Name $adapter.name | Get-VDPortgroup    
        Write-host Changing $VM NIC from $old_network to $temp_network
        Get-NetworkAdapter -VM $VM.name -Name $adapter.name | Set-NetworkAdapter -Portgroup $temp_network -Confirm:$false
        Write-host Changing $VM NIC from $temp_network to $old_network
        Get-NetworkAdapter -VM $VM.name -Name $adapter.name | Set-NetworkAdapter -Portgroup $old_Network -Confirm:$false
    }
  }
}

Pass in the VM names as args. So call it with the following .\fix-nics.ps1 VMNAME1 VMNAME2
 
You need a loop. Populate the existing NIC's into an array and iterate through it when updating.

For single NIC VMs the array will only have one member. For multi-NIC, it will have n members.

Writing your scripts to assume that everything is an array of 1..n objects is a much more reliable approach.
 
Back
Top