PowerShell / CLI:“Foreach”循环多个数组 [英] PowerShell/CLI: "Foreach" loop with multiple arrays
问题描述
我现在试图修改脚本以利用数组,以便循环通过大量的虚拟机。
我遇到的麻烦是在foreach循环中使用来自两个数组的变量。
对于$ vm_name中的每个虚拟机,我需要设置在$ memory_gb中找到的相应内存量。
这就是我有(它目前为所有的虚拟机设置相同数量的内存(1))....
$ vm_name = @(OMAC-SBXWIN7AJM,OMAC-SBXWIN2012R2AJM,OMAC-SBXWIN2008R2AJM)
$ memory_gb = 2,4,4
#设置VM MEMORY
Write-Host'现在设置VM MEMORY'
foreach($ vm_name中的$ objItem)
{Set-VM -VM $ vm_name -MemoryGB 1 -confirm:$ false
Break
}
http://i.stack.imgur.com/E9hfY.png
...我已经尝试在第一个嵌套的第二个foreach循环内,无济于事。
如何编写脚本使每个VM在$ vm_name中,获取在$ memory_gb中找到的相应的内存量?
您有2个选项。首先(而不是我会建议)是一个For()循环。它会像这样:
$ $ p $ code $ For($ I = 0; $ I -lt $ vm_name.count; $ I ++) {
Set-VM -VM $ vm_name [$ I] -MemoryGB $ memory_gb [$ I] -confirm:$ false
}
更好的方法是把它放在一个带有 VMName,Memory
标题的CSV文件中,然后列出每个VM和你想要的内存。然后运行如下所示:
Import-CSV C:\Path\To\File.CSV | ForEach {Set-VM -VM $ _。VMName -MemoryGB $ _。memory -confirm:$ false}
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?
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}
这篇关于PowerShell / CLI:“Foreach”循环多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!