Search code examples
powershellpowershell-2.0powercli

Powershell - Call Unique Values in a ForEach loop from Two Variables to execute a PowerCLI command


I am trying to write a script to bring network cards back online, after a port conflict.

I have a list of VMs stored in one variable ($VDILIST) and have a list of available port numbers stored in a second variable ($FREEPORT).

How do I assign a port number to each of the new VM Network cards. I included a line (remarked out) how to do it for one. I know how to either process a single list ForEach loop. However, I can not figure out how to process these values from two seperate variables.

Port               VM
----              ----
01                 PC-A 
02                 PC-B
03                 PC-C
04                 PC-D

I want to assign Port 01 ot PC-A then move to the next and assign Port 02 to PC-B. Then continue on from there.

Thank you for your help.

$VDI = "vdi-win7v5-*"
$PORTGROUP = "Enterprise"

$VDILIST = @(Get-VM $VDI)
$FREEPORT = Get-dvPgFreePort -PortGroup $PortGroup -Number ($VDILIST).count

###USED FOR SINGLE COMPUTER
###Get-VM vdi-win7v2-30 |Get-NetworkAdapter|Set-NetworkAdapter -PortKey $FREEPORT -DistributedSwitch chsdc-nexus1000v -Connected:$TRUE -Confirm:$False

Solution

  • Assuming that $VDILIST and $FREEPORT have exactly the same number of items:

    For ($i = 0; $i -lt $VDILIST.count; $i++)
    {
        Get-VM $VDILIST[$i] |Get-NetworkAdapter|Set-NetworkAdapter -PortKey $FREEPORT[$i] -DistributedSwitch chsdc-nexus1000v -Connected:$TRUE -Confirm:$False
    }