我想在一个循环中使用 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)
如何组合两个数组的元素以获得这样的结果?
$Path = (“A”, “b”,”c”)
$Dir_List = (“1″,”2″,”3″,”4”)
foreach ($Path in $Path)
{
#$URL_List = $()
ForEach ($Dir_List in $Dir_List){$Path+$Dir_List}
}
现在: A1 A2 A3 A4 b4 c4 必需的: A1 A2 A3 A4 b1 b2 b3 b4 c1 c2 c3 c4