如何停止在 ForEach 中多次遍历整个列表?

How can I stop iterating through entire list multiple times in ForEach?

如何将一个列表中的 1 个 IP 地址应用到另一个列表中的 1 个服务器? 然后移动到下一个IP并将其应用于下一个服务器。

servers.txt 看起来像:

server1
server2
server3

ip.txt 看起来像:

10.1.140.80
10.1.140.81
10.1.140.83

我只想浏览列表并申请

10.1.140.80 to server1
10.1.140.81 to server2
10.1.140.83 to server3

相反,我的脚本将所有 3 个 IP 地址应用到每台服务器。 我不想一遍又一遍地遍历所有 IP 地址。

如何正确地遍历列表并更正此问题?

$computers = "$PSScriptRoot\servers.txt"
$iplist        = gc "$PSScriptRoot\ip.txt"

function changeip {
    get-content $computers | % {
        ForEach($ip in $iplist) {

            # Set IP address
            $remotecmd1 = 'New-NetIPAddress -InterfaceIndex 2 -IPAddress $ip -PrefixLength 24 -DefaultGateway 10.1.140.1'

            # Set DNS Servers  -  Make sure you specify the server's network adapter name at -InterfaceAlias
            $remotecmd2 = 'Set-DnsClientServerAddress -InterfaceAlias "EthernetName" -ServerAddresses 10.1.140.5, 10.1.140.6'

            Invoke-VMScript -VM $_ -ScriptText $remotecmd1 -GuestUser Administrator -GuestPassword PASSWORD -ScriptType PowerShell
            Invoke-VMScript -VM $_ -ScriptText $remotecmd2 -GuestUser Administrator -GuestPassword PASSWORD -ScriptType PowerShell

        }
    }
}

changeip

使用 Get-Content cmdlt 将两个文件内容放入一个数组中,然后按数组位置提取各个值。您可能需要一些逻辑来检查数组大小是否匹配,如果不匹配则进行自定义处理。在上面的示例中,您基本上是在另一个 foreach 循环中放置一个 for each 循环,这给了您所看到的行为。

$computers = GC "C:\server.txt"
$iplist   = GC "C:\ip.txt"

for ($i = 0; $i -lt $iplist.Count ; $i++) {
    Write-host  ("{0}  -  {1}" -f $computers[$i],$iplist[$i])
}

或者,如果您习惯于将 foreach 逻辑用于一个列表,而不是使用 for 循环进行基本迭代,那么您可以在 foreach 循环中添加一个计数器。然后您可以查找已解析的 iplist 数组的数组索引。它基本上做同样的事情..

$computers = "C:\server.txt"
$iplist   = GC "C:\ip.txt"

get-content $computers | % {$counter = 0} {
Write-host  ("{0}  -  {1}" -f $_,$iplist[$counter])
$counter++
}

同样为了清楚起见,请在这一行中注明:

"get-content $computers | %"

% 实际上是 ForEach-Object 的别名,这就是为什么您在看到的 foreach 输出中获取 foreach 的原因。