将测试连接转换为布尔值



我使用的是Powershell版本2,因此无法使用Ping Host有没有一种方法可以将Ping主机视为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的服务器输出"废话",就好像我不能ping它一样。

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

测试连接:测试与计算机服务器的连接失败:由于缺少资源而出错,行:1字符:22+if($(测试连接<<服务器-计数1)received-eq 1){写主机"布拉"}其他{写宿主"布拉"}+类别信息:资源不可用:(服务器:字符串)[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。你想得太多了;只需使用CCD_ 3。若要取消显示错误消息,请使用-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

最新更新