繁体   English   中英

将Test-Connection转换为Boolean

[英]Convert Test-Connection into Boolean

我正在使用Powershell版本2,因此我无法使用Ping-Host,如此处所述有没有办法将Ping-Host视为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字符:22 + if($(测试连接<<<< 服务器 -帐户1)。接收-eq 1){write- host“blah”} else {write-host“blah blah”} + CategoryInfo:ResourceUnavailable:( server :String)[Test-Connection],PingException + FullyQualifiedErrorId:TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand

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

怎么修?

试试-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

Received不是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"}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM