PowerShell/CLI: "Foreach" loop with multiple arrays

James McCallister picture James McCallister · Aug 7, 2014 · Viewed 27.3k times · Source

I have a PowerCLI script that powers off a VM, changes its memory and cpu, and then powers it back on. I've adapted the script to utilize variables. This all works perfectly.

I'm now trying to modify the script to utilize arrays, in order to cycle through numerous VMs. The script portions that powers off and powers on the VMs works perfectly.

The trouble I'm having is using variables from two arrays in a foreach loop.

For each VM in $vm_name, I need to set the corresponding amount of memory found in $memory_gb.

This is what I have (it currently sets the same amount of memory ("1") for all of the VMs)....

$vm_name = @("OMAC-SBXWIN7AJM", "OMAC-SBXWIN2012R2AJM", "OMAC-SBXWIN2008R2AJM")
$memory_gb = 2,4,4

# SET THE VM MEMORY
Write-Host 'NOW SETTING THE VM MEMORY'
foreach ($objItem in $vm_name)
{Set-VM -VM $vm_name -MemoryGB 1 -confirm:$false 
Break
}

http://i.stack.imgur.com/E9hfY.png

...I've tried nesting a second foreach loop inside of the first, to no avail.

How do write the script so each VM in $vm_name, gets the corresponding amount of memory found in $memory_gb?

Answer

Marek Toman picture Marek Toman · Jan 12, 2015

You can use Zip function:

function Zip($a1, $a2) {
    while ($a1) {
        $x, $a1 = $a1
        $y, $a2 = $a2
        [tuple]::Create($x, $y)
    }
}

Usage:

zip 'a','b','c' 1,2,3 |% {$_.item1 + $_.item2}

Result:

a1
b2
c3