如何在PowerShell脚本中实现联网测试并返回布尔值用于条件判断?
解决PowerShell测试网络连接的布尔值判断问题
你的问题核心是Test-NetConnection返回的不是布尔值,而是包含连接状态的对象——PowerShell的if语句只要判断的对象非空,就会视为$true,所以不管连接成功与否,都会执行echo "OK"分支。
以下是两种可靠的解决方法:
方法一:用Test-Connection直接返回布尔值
Test-Connection自带-Quiet参数,会直接返回$true或$false,同时可以通过参数抑制错误输出:
if (Test-Connection 192.168.1.222 -Count 1 -Quiet -ErrorAction SilentlyContinue) { Write-Host "OK" } else { Write-Host "Not OK" }
-Count 1:只发送一次ICMP请求,加快测试速度-Quiet:强制返回布尔值-ErrorAction SilentlyContinue:屏蔽连接失败时的错误提示
方法二:检查Test-NetConnection的属性值
如果坚持用Test-NetConnection,可以捕获它返回的对象,直接判断PingSucceeded属性(这是一个布尔值):
$connResult = Test-NetConnection 192.168.1.222 -ErrorAction SilentlyContinue if ($connResult.PingSucceeded) { Write-Host "OK" } else { Write-Host "Not OK" }
如果需要测试特定端口连通性,可添加-Port参数,判断TcpTestSucceeded属性:
$connResult = Test-NetConnection 192.168.1.222 -Port 80 -ErrorAction SilentlyContinue if ($connResult.TcpTestSucceeded) { Write-Host "Port 80 is reachable" } else { Write-Host "Port 80 is not reachable" }
内容的提问来源于stack exchange,提问作者Sloan Thrasher
相关产品推荐
相关产品推荐

