【问题标题】:How can I stop iterating through entire list multiple times in ForEach?如何在 ForEach 中停止多次遍历整个列表?
【发布时间】:2019-05-22 18:39:43
【问题描述】:

如何将一个列表中的 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

【问题讨论】:

    标签: powershell powercli


    【解决方案1】:

    使用您的 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++
    }
    

    为了清楚起见,请注意这一行:

    “获取内容 $computers | %”

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 2011-01-21
      相关资源
      最近更新 更多