New-VMHostNetworkAdapter - 在 PowerCLI 中使用 foreach 对象循环 IP 地址

New-VMHostNetworkAdapter - Looping IP address with foreach-object in PowerCLI

我正在尝试使用 PowerCLI 为 vCenter 中的现有 ESXi 主机创建 vmkernel。

$esxiHosts = @("esxi21.v.lab", "esxi22.v.lab", "esxi23.v.lab", "esxi24.v.lab", "esxi25.v.lab")
$vmhosts = Get-VMHost -Name $esxiHosts
foreach ($i in 31..35)
 {
   $ipa = "192.168.2.$i"
   write-host $vmhosts
   $esxiHosts | foreach-object {New-VMHostNetworkAdapter $_ -PortGroup ManagementNetwork2 -IP $ipa -subnetmask 255.255.255.0 -VirtualSwitch vSwitch0 -ManagementTrafficEnabled $true}
 }

它为每个主机创建 vmkernels,但是为所有主机分配相同的 IP 地址,然后也显示以下错误。

New-VMHostNetworkAdapter : 26 Sep 2019 4:21:17 PM       New-VMHostNetworkAdapter                An error occurred during host configuration. Operation failed, diagnostics report: A vmkernel
nic for the connection point already exists:
At line:5 char:30
+ ... ach-object {New-VMHostNetworkAdapter $_ -PortGroup ManagementNetwork2 ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-VMHostNetworkAdapter], PlatformConfigFault
    + FullyQualifiedErrorId : Client20_VmHostServiceImpl_NewVMHostNetworkAdapter_ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.Host.NewVMHostNetworkAdapter

我的理解是这是由于循环内的 foreach-object 运行,但如果我不这样做,我就不能仅使用 for each 循环来迭代 IP 地址,或者我可以?

解决此问题的一种方法可能是使用计数器变量,因为您的第 4 个八位字节是连续的。类似于以下内容:

$esxiHosts = @("esxi21.v.lab", "esxi22.v.lab", "esxi23.v.lab", "esxi24.v.lab", "esxi25.v.lab")
$vmhosts = Get-VMHost -Name $esxiHosts
$i = 31
foreach ($vmh in $vmhosts) {
   $ipa = "192.168.2.$i"
   Write-Host $vmh
   New-VMHostNetworkAdapter -VMHost $vmh -PortGroup ManagementNetwork2 -IP $ipa -subnetmask 255.255.255.0 -VirtualSwitch vSwitch0 -ManagementTrafficEnabled $true
   $i++
}