我使用的是 Powershell 版本 2,所以我无法使用 Ping-Host,如此处所述
Is there a way to treat Ping-Host as a boolean in PowerShell?
我可以使用测试连接,即
Test-Connection *ip_address* -count 1
我试图把它变成一个 bool 值,但它不起作用
if ($(test-connection server -count 1).received -eq 1) { write-host "blah" } else {write-host "blah blah"}
我能够ping通的服务器输出“blah blah”,就好像我无法ping通它一样。
另一方面,如果我 ping 无法访问的服务器,则会收到错误消息
Test-Connection : Testing connection to computer server failed: Error due to lack of resources At line: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
最后它仍然输出“blah blah”。
怎么修?
最佳答案
收到 不是 的对象的属性测试连接返回,所以 $(test-connection server -count 1).received
评估为空。你想多了;只需使用 if (Test-Connection -Count 1)
.要禁止显示错误消息,请使用 -ErrorAction SilentlyContinue ,或通过管道将命令发送到 外空 .以下任一方法都有效:
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"}
关于powershell - 将测试连接转换为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17953692/