在我看来
try
/
catch
会的
确切地
您的问题:
try {
Test-Connection -Computer $pc -Count 2 -EA Stop | ForEach-Object {
[PSCustomObject]@{
LocalPC = $env:COMPUTERNAME
'Tested-Server' = $pc
Bytes = $_.buffersize
Time = $_.ResponseTime
RemotePort = $test_netconnection.RemotePort
TcpTestSucceeded = $test_netconnection.TcpTestSucceeded
}
}
} catch {
"The computer $pc is not online."
}
然而,就个人而言,我更喜欢保持可ping主机和不可ping主机的输出格式相同(增加一列用于“在线”状态)。用于该用途
-ErrorAction SilentlyContinue
要抑制错误,请收集
Test-Connection
在变量中,然后根据该变量是否为空来构建自定义对象。
$test_connection = Test-Connection -Computer $pc -Count 2 -EA SilentlyContinue
if ($test_connection) {
$test_connection | ForEach-Object {
[PSCustomObject]@{
LocalPC = $env:COMPUTERNAME
'Tested-Server' = $pc
Online = $true
Bytes = $_.buffersize
Time = $_.ResponseTime
RemotePort = $test_netconnection.RemotePort
TcpTestSucceeded = $test_netconnection.TcpTestSucceeded
}
}
} else {
[PSCustomObject]@{
LocalPC = $env:COMPUTERNAME
'Tested-Server' = $pc
Online = $false
Bytes = $null
Time = $null
RemotePort = $test_netconnection.RemotePort
TcpTestSucceeded = $test_netconnection.TcpTestSucceeded
}
}
作为补充说明,我不建议使用派生信息(
$_.PSComputerName
,则,
$test_netconnection.ComputerName
)有原始信息的地方(
$env:COMPUTERNAME
,$pc`)。