嵌套循环未按预期powershell工作



你好,我正在创建一个创建接口ips历史记录的脚本,但我在嵌套循环中遇到了问题。

for($r = 0; $r -lt $iface.Count; $r++){
for($m = 0; $m -lt $iface.Count; $m++){
if($ifaceold[$r] -match $iface[$m]){
Write-Host "name true"  " "  $ifaceold[$r]  " "  $iface[$m]
if($ifaceold[$r] -match $ifaceip[$m]){

Write-Host "ip true" " "  $ifaceold[$r]  " " $iface[$m]  " "  $ifaceip[$m]
}else{
Write-Host "ip false"   " "  $ifaceold[$r]  " "  $iface[$m]  " "  $ifaceip[$m]
}
}else{
Write-Host "name false"  " "  $ifaceold[$r]  " "  $iface[$m]
}
}
}
Result:
name true   Ethernet 6 10.10.2.5   Ethernet 6
ip false   Ethernet 6 10.10.2.5   Ethernet 6   10.10.2.1
name false   Ethernet 6 10.10.2.5   Ethernet 5
name false   Ethernet 6 10.10.2.5   Ethernet 4
name false   Ethernet 5 10.10.1.1   Ethernet 6
name true   Ethernet 5 10.10.1.1   Ethernet 5
ip true   Ethernet 5 10.10.1.1   Ethernet 5   10.10.1.1
name false   Ethernet 5 10.10.1.1   Ethernet 4
name false   Ethernet 4 192.168.77.53   Ethernet 6
name false   Ethernet 4 192.168.77.53   Ethernet 5
name true   Ethernet 4 192.168.77.53   Ethernet 4
ip true   Ethernet 4 192.168.77.53   Ethernet 4   192.168.1.53

由于某些原因,第二个循环无法按预期工作。例如,$iface将等于以太网6,它将匹配以以太网6、以太网4和以太网5为值的$ifaces阵列。如果$ifaceold与$iface匹配,那么它将进入下一个If序列,这对我来说是坏的。我现在想将以太网6 ip与$ifaceip值匹配,如果它们匹配,那么只需将输出设为true。但正如您所看到的,它与名称匹配了3次,但每个接口的ip只有一次。有人能告诉我为什么我的第二个循环不起作用吗?

好的,我想好了我必须做什么。在匹配接口名称并开始比较ip地址之后,第二个循环必须在if case内部

for($r = 0; $r -lt $iface.Count; $r++){
for($m = 0; $m -lt $iface.Count; $m++){    
if($ifaceold[$r] -match $iface[$m]){
Write-Host "name true"  " "  $ifaceold[$r]  " "  $iface[$m]
for($q = 0; $q -lt $iface.Count; $q++){
if($ifaceold[$r] -match $ifaceip[$q]){

Write-Host "ip true" " "  $ifaceold[$r]  " = " $iface[$q]  " "  $ifaceip[$q]
}else{
Write-Host "ip false"   " "  $ifaceold[$r]  " = "  $iface[$q]  " "  $ifaceip[$q]
}
}
}else{
Write-Host "name false"  " "  $ifaceold[$r]  " = "  $iface[$m]
}
}
}
Result: 
name true   Ethernet 6 10.10.2.5   
ip false   Ethernet 6 10.10.2.5   Ethernet 6   10.10.2.1
ip false   Ethernet 6 10.10.2.5   Ethernet 5   10.10.1.1
ip false   Ethernet 6 10.10.2.5   Ethernet 4   192.168.1.53
name true   Ethernet 5 10.10.1.1   
ip false   Ethernet 5 10.10.1.1   Ethernet 6   10.10.2.1
ip true   Ethernet 5 10.10.1.1   Ethernet 5   10.10.1.1
ip false   Ethernet 5 10.10.1.1   Ethernet 4   192.168.1.53
name true   Ethernet 4 192.168.77.53   
ip false   Ethernet 4 192.168.77.53   Ethernet 6   10.10.2.1
ip false   Ethernet 4 192.168.77.53   Ethernet 5   10.10.1.1
ip true   Ethernet 4 192.168.77.53   Ethernet 4   192.168.1.53

最新更新