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

Use 2 arrays in one loop

我想在一个循环中使用 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

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

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

$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
}

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

$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 描述的哈希表方法。但是,此方法对您的代码的更改最少。

感谢您提供的信息。你建议的一些其他脚本对我有用,但我最终使用以下方法实现了这一点。 首先我生成了一系列这样的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")"}

不完全是这样,但有点像这样。

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

$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)