powershell - 将测试连接转换为 bool 值

标签 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

我试图把它变成一个 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/

相关文章:

powershell - 从 AD OU 获取 WmiObject

powershell - Install-ADServiceAccount的目的

java - JAVA中发送ctrl+c关闭ping请求

docker - Ping直到Docker启动或超时

Android 应用程序开发 - 使用 Android 手机开始与计算机设备聊天

powershell - 使用 NuGet uninstall.ps 删除解决方案文件夹

visual-studio-2010 - Visual Studio 2010 构建后步骤中的 Powershell 脚本

powershell - |之间的差异和 $

linux - Ping 状态和返回

java - 为什么我无法 ping 通计算机?