powershell - Powershell 意外行为
问题描述
我隔离了一些代码,但出现了意外行为。
代码:
$objects = @(
[pscustomobject]@{server="google.com"; some_other_props='some_str'},
[pscustomobject]@{some_other_props='some_str'},
[pscustomobject]@{server='google.com'; some_other_props='some_str'}
)
$objects | % {
try{
$result = Test-Connection $_.server
}catch [System.Management.Automation.ParameterBindingException] {
Write-Host "no server to ping"
}
if($result){
Write-Host ok
}
}
预期输出:
ok
no server to ping
ok
实际输出:
ok
no server to ping
ok
ok
我在这里做错了什么?第三个确定从哪里来??
解决方案
您的 catch 不会中断当前的执行,因此无论代码是否引发异常,您的 if 语句都会运行。
把你的 if 语句放在你的 catch 的底部。
$objects | % {
try{
$result = Test-Connection $_.server
if($result) {
Write-Host ok
}
} catch [System.Management.Automation.ParameterBindingException] {
Write-Host "no server to ping"
}
}
推荐阅读
- c# - SSIS中脚本任务中的多线程现有C#
- html - 如何将菜单与桌面右侧对齐?
- git - 将由多个提交组成的功能合并到另一个项目中
- javascript - Chrome 扩展 'No-Access-Control-Allow-Origin' api 调用命中服务器但返回错误
- reactjs - 使用 render() 返回编写单元测试
- apache-spark - Spark 1.6 - df.write.save() 和 df.write.parquet() 有什么区别
- sql - 如何选择至少一个 json 元素与某些条件匹配的 postgres 行?
- html - 颠倒图像问题 - 需要解决方案
- sql - 如果“from”子句不匹配任何结果,如何编写空表?
- excel - Excel VBA 矩阵错误 1004