在 Powershell 中优雅地处理点源故障

Bru*_*uno 1 powershell

所以我有一个使用点源的脚本

$Dependencies = "Script1","Script2","Script3"
$Dependencies | % { . ".\$( $_ ).ps1" }
Run Code Online (Sandbox Code Playgroud)

我尝试使用Try { } Catch { }捕获错误但将脚本导入 try 和 catch 的范围。

检测点源导入失败的最简洁方法是什么?

通常我可以设置ErrorActionStop并强制函数抛出错误,但我似乎无法通过点源来做到这一点。

更新

最后证明 try and catch 确实有效。这是我修改后的脚本

$Dependencies = "Script1","Script2","Script3"
$Dependencies |
    ForEach-Object {
        Try { . ".\$( $_ ).ps1" } 
        Catch { Throw }
    }
Run Code Online (Sandbox Code Playgroud)

Paw*_*Dyl 5

我敢打赌你错误地使用了 try-catch。看一下下面的代码片段(为了简单起见进行了扩展):

$Dependencies = "Script1","Script2","Script3"
$Dependencies | % {
    try {
        $psFile = ".\$($_).ps1"
        . $psFile
    } catch {
        Write-Host "Failed to execute $psFile"
    }
}
Run Code Online (Sandbox Code Playgroud)