将Test-Connection转换为Boolean

时间:2013-07-30 17:37:33

标签: powershell ping

我正在使用Powershell版本2,因此我无法使用Ping-Host,如此处所述 Is there a way to treat Ping-Host as a boolean in PowerShell?

我可以使用测试连接,即

Test-Connection *ip_address* -count 1

我正在尝试将其变为布尔值,但它无法正常工作

if ($(test-connection server -count 1).received -eq 1) { write-host "blah" } else {write-host "blah blah"}

我能ping的服务器输出“blah blah”,好像我无法ping它。

另一方面,如果我ping无法访问的服务器,我会收到错误消息

  

测试连接:测试与计算机服务器的连接失败:   由于缺乏资源导致的错误在第1行:char:22   + if($(test-connection<<<< server -count 1).received -eq 1){write-host“blah”} else {write-host“blah blah “}       + CategoryInfo:ResourceUnavailable:( server :String)[Test-Connection],PingException       + FullyQualifiedErrorId:TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

最后它仍然输出“等等”。

如何解决?

3 个答案:

答案 0 :(得分:20)

尝试-Quiet开关:

Test-Connection server -Count 1 -Quiet    

-Quiet [<SwitchParameter>]
    Suppresses all errors and returns $True if any pings succeeded and $False if all failed.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Accept wildcard characters?  false

答案 1 :(得分:10)

收到不是 Test-Connection 返回的对象的属性,因此$(test-connection server -count 1).received的计算结果为null。你过度思考它;只需使用if (Test-Connection -Count 1)。要禁止显示错误消息,请使用 -ErrorAction SilentlyContinue ,或将命令传递给 Out-Null 。以下任何一种都可以使用:

if (Test-Connection server -Count 1 -ErrorAction SilentlyContinue) { write-host "blah" } else {write-host "blah blah"}

if (Test-Connection server -Count 1 | Out-Null) { write-host "blah" } else {write-host "blah blah"}

答案 2 :(得分:0)

我们在生产中使用的更好的一个衬垫

function test_connection_ipv4($ipv4) { if (test-connection $ipv4 -Count 1 -ErrorAction SilentlyContinue ) {$true} else {$false} }

用法示例1:

test_connection_ipv4 10.xx.xxx.50
True

用法示例2:

test_connection_ipv4 10.xx.xxx.51
False