将2个列表与条件结合在PowerShell中?

时间:2018-10-11 11:11:32

标签: list powershell-v5.0

$computerips = 'IP 1','IP 1','IP 3','IP 4'
$computername = "IP 1 NAME","IP 2 NAME","IP 3 NAME","IP 3 NAME"

For ($i=0; $i -lt $computerips.count; $i++) {
    $computerips[$i]+$computername[$i]
}

让我们假设$ computerips是一个IP地址列表,而$ computername是一个IP地址别名/名称列表。

如何在上述代码中基于true或false包含条件(测试连接),并且仅使用状态为OK或NOK的IP地址名称?

即我需要这样的东西:

foreach ($computer in $computerips) {
    if (Test-Connection -ComputerName $computer -Count 3 -EA SilentlyContinue) {
        Write-Host $computername "Online"
    }
    else {
        Write-Host $computername "Offline"
    }
}

在将名称发送到输出之前,我需要以某种方式将其与IP匹配。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

$computerips = '10.10.10.0','10.10.10.1','10.10.10.2'
$computername = "10.10.10.0 Server1","10.10.10.1 Server2","10.10.10.2 Server3"
foreach ($computer in $computerips) {
    if (Test-Connection -ComputerName $computer -Count 3 -EA SilentlyContinue) {
        write-host "$((($computername -match $computer).replace($computer,'')).trim()) Online"
    }
    else {
        write-host "$((($computername -match '$computer').replace('$computer','')).trim()) Offline"
    }
}

输出

Server1在线 Server2离线 Server3在线版