如何将一个列表中的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
答案 0 :(得分:2)
使用Get-Content cmdlt将两个文件内容都放入数组中,然后按数组位置提取各个值。您可能需要一些逻辑来检查数组大小是否匹配,如果不匹配,则进行自定义处理。在上面的示例中,您基本上是将for每个循环放在另一个foreach循环内,这将使您看到自己的行为。
$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的原因。