PowerShell/CLI: “Foreach” loop with multiple arrays

Question:

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)….

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:

You have 2 options. First (and not what I would suggest) is a For() loop. It would go something like this:


The better way would be to put it in a CSV with headers like VMName, Memory and then list each VM and the memory you want in it. Then run something like:

Source:

PowerShell/CLI: “Foreach” loop with multiple arrays by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply