在try-finally块中路径不存在的Powershell调用运算符(&)导致终止错误

时间:2019-04-09 09:01:46

标签: powershell error-handling call try-finally

我有一个Powershell脚本(script1.ps1),其内容如下:

Write-Output "Script1 - Start"
& ".\nonexistent.ps1"
Write-Output "Script1 - End"

nonexistent.ps1显然是一个不存在的文件。 我有另一个脚本(script2.ps1),有时它会称为script1.ps1:

& ".\script1.ps1"

运行script2.ps1会生成以下输出:

Script1 - Start
& : The term '.\nonexistent.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\scripts\script1.ps1:2 char:3
+ & ".\nonexistent.ps1"
+   ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (.\nonexistent.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Script1 - End

因此,在这种情况下,运行不存在的脚本是一个非终止错误,因为执行后的代码没有问题。

我的问题如下:我用以下代码替换调用script1.ps1的代码:

Try {
    & ".\script1.ps1"
} Finally {
    Write-Output "Script2 - Finally"
}

输出变为:

Script1 - Start
Script2 - Finally
& : The term '.\nonexistent.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\scripts\script1.ps1:2 char:3
+ & ".\nonexistent.ps1"
+   ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (.\nonexistent.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

因此,在这种情况下,调用不存在的脚本成为终止错误,因为此后的代码不执行。更奇怪的是,该错误实际上是在finally块运行之后出现的。我的问题是:为什么会发生这种情况?如果我不想在使用try-finally块时“意外地”将非终止错误转换为终止错误,那么正确的解决方案是什么?

0 个答案:

没有答案