PowerShell/CLI: "Foreach" loop with multiple arrays
You have 2 options. First (and not what I would suggest) is a For() loop. It would go something like this:
For($I=0;$I -lt $vm_name.count;$I++){
Set-VM -VM $vm_name[$I] -MemoryGB $memory_gb[$I] -confirm:$false
}
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:
Import-CSV C:\Path\To\File.CSV | ForEach{Set-VM -VM $_.VMName -MemoryGB $_.memory -confirm:$false}
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
Another, more compact, solution is to use a hashtable:
$vms = @{"OMAC-SBXWIN7AJM" = 2; "OMAC-SBXWIN2012R2AJM" = 4; "OMAC-SBXWIN2008R2AJM" = 4}
# SET THE VM MEMORY
Write-Host 'NOW SETTING THE VM MEMORY'
foreach ($vm in $vms.getEnumerator()){
Set-VM -VM $vm.Name -MemoryGB $vm.Value -confirm:$false
}