在一个循环中使用2个数组

时间:2015-07-06 18:41:07

标签: powershell powercli

我想在一个循环中使用2个数组,但是我每次都失败了以找出方法?

$hosts = "1.1.1.1,2.2.2.2,3.3.3.3"
$vmotionIPs = "1.2.3.4,5.6.7.8,7.8.9.0"
foreach ($host in $hosts) ($vmotionIP in $vmotionIPs)
  New-VMHostNetworkAdapter -VMHost $host-VirtualSwitch myvSwitch `
    -PortGroup VMotion -IP $vmotionIP -SubnetMask 255.255.255.0 `
    -VMotionEnabled $true

我知道上面的语法错了,但我希望它能传达我的目标。

4 个答案:

答案 0 :(得分:3)

最直接的方法是使用哈希表:

$hosts = @{
    "1.1.1.1" = "1.2.3.4" # Here 1.1.1.1 is the name and 1.2.3.4 is the value
    "2.2.2.2" = "5.6.7.8"
    "3.3.3.3" = "7.8.9.0"
}

# Now we can iterate the hashtable using GetEnumerator() method.
foreach ($hostaddr in $hosts.GetEnumerator()) { # $host is a reserved name
    New-VMHostNetworkAdapter -VMHost $hostaddr.Name -VirtualSwitch myvSwitch `
        -PortGroup VMotion -IP $$hostaddr.Value -SubnetMask 255.255.255.0 `
        -VMotionEnabled $true
}

答案 1 :(得分:3)

首先,您的阵列不是数组。他们只是字符串。要成为数组,您需要将它们指定为:

$hosts = "1.1.1.1","2.2.2.2","3.3.3.3";
$vmotionIPs = "1.2.3.4","5.6.7.8","7.8.9.0";

其次,$host是保留变量。你应该避免使用它。

第三,我假设您希望第一个主机使用第一个vmotionIP,第二个主机使用第二个vmotionIP等。

因此,执行此操作的标准方法是:

$hosts = "1.1.1.1","2.2.2.2","3.3.3.3";
$vmotionIPs = "1.2.3.4","5.6.7.8","7.8.9.0";

for ($i = 0; $i -lt $hosts.Count; $i++) {
    New-VMHostNetworkAdapter -VMHost $hosts[$i] `
        -VirtualSwitch myvSwitch `
        -PortGroup VMotion `
        -IP $vmotionIPs[$i] `
        -SubnetMask 255.255.255.0 `
        -VMotionEnabled $true;
}

或者您可以使用哈希表方法@AlexanderObersht描述。但是,此方法最少改变您的代码。

答案 2 :(得分:0)

感谢您提供的信息。你的建议为我工作了一些其他的脚本,但我最终使用以下内容实现了这一目标。 首先我生成了一系列这样的IP地址

$fixed = $host1.Split('.')[0..2]
$last = [int]($host.Split('.')[3])
$max = Read-Host "Maximum number of hosts that you want to configure?"
$max_hosts = $max - 1
$hosts = 
$last..($last + $max_hosts) | %{
[string]::Join('.',$fixed) + "." + $_
}

然后我做了

$vMotion1_ip1 = Read-Host "the 1st vmotion ip of the 1st host?"
$fixed = $vMotion1_ip1.Split('.')[0..2]
$last = [int]($vMotion1_ip1.Split('.')[3])
$max_hosts = $max - 1
$vMotions = 
$last..($last + $max_hosts) | %{
[string]::Join('.',$fixed) + "." + $_
}
$first = [string]::Join('.',$fixed) + "." + $_

foreach ($vmhost in $vMotions) {write-host "$vmhost has the following      network ("$first$(($last++))", "255.255.255.0")"}

并不完全像这样但是这样的事情。

答案 3 :(得分:0)

谢谢大家的回答。我最终使用了do而不是。这允许我们同时循环遍历任意数量的数组,或者在一个循环中包含多个数组。

$hosts  = @("1.1.1.1","2.2.2.2","3.3.3.3")
$vmotionIPs  = @("1.2.3.4","5.6.7.8","7.8.9.0")
[int]$n = 0
do
{
$vmhost = $hosts[$n]
$vmotionIP = $vmotionIPs[$n]
New-VMHostNetworkAdapter -VMHost $vmhost-VirtualSwitch myvSwitch -PortGroup VMotion -IP $vmotionIP -SubnetMask 255.255.255.0 -VMotionEnabled $true
$n++
} while ($n -lt $hosts.count)