将测试连接错误转换为消息

时间:2014-03-27 18:19:38

标签: powershell

我使用以下代码获取列表中计算机的状态和IP地址:

    $csv = Get-Content TEST_MACHINES.csv

    foreach ($computer in $csv)
    {
try
{
    Test-Connection $computer -Count 1 | Select-Object Address, IPV4Address
}
catch [System.Net.NetworkInformation.PingException]
{
    '$computer is offline.'
}
    }

目标是获取每台机器的IP地址,如果机器处于脱机状态,打印" $计算机处于脱机状态。"

但是,它不会捕获错误并显示消息,而是显示整个测试连接错误。如何在出现错误时才显示我的消息?

1 个答案:

答案 0 :(得分:4)

Try/Catch中,仅在终止错误时调用Catch块。将-ErrorAction Stop添加到Test-Connection以强制错误终止,以便Catch块运行:

Test-Connection $computer -Count 1 -ErrorAction Stop | Select-Object Address, IPV4Address