首页 > 解决方案 > 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

我在这里做错了什么?第三个确定从哪里来??

标签: powershell

解决方案


您的 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"
    }  
}

推荐阅读