我一直在寻找一种方法,在函数中发生不可恢复的错误时终止PowerShell (PS1)脚本。例如:

function foo() {
    # Do stuff that causes an error
    $host.Exit()
}

当然,没有$host.Exit()这样的东西。有$host.SetShouldExit(),但这实际上关闭了控制台窗口,这不是我想要的。我需要的是一些相当于Python的sys.exit(),它将简单地停止当前脚本的执行,而不需要进一步的告别。

编辑:是的,只是退出。咄。


当前回答

我碰巧发现Break <UnknownLabel>(例如,简单地打破脚本,标签脚本不存在)似乎打破了整个脚本(甚至从一个函数中),并保持宿主存活。 通过这种方式,你可以创建一个函数,在不知道当前范围(并创建标签)的情况下,从任何地方(例如递归循环)中断脚本:

Function Quit($Text) {
    Write-Host "Quiting because: " $Text
    Break Script
} 

其他回答

您应该使用exit关键字。

也许用“陷阱”更好。PowerShell trap指定当发生终止或错误时要运行的代码块。类型

Get-Help about_trap

了解更多关于trap语句的信息。

抛出一个异常会很好,特别是当你想澄清错误原因时:

throw "Error Message"

这将生成一个终止错误。

Write-Error用于非终止错误,throw用于终止错误

The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output. Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection. To declare a terminating error, use the Throw keyword. For more information, see about_Throw (http://go.microsoft.com/fwlink/?LinkID=145153).

我碰巧发现Break <UnknownLabel>(例如,简单地打破脚本,标签脚本不存在)似乎打破了整个脚本(甚至从一个函数中),并保持宿主存活。 通过这种方式,你可以创建一个函数,在不知道当前范围(并创建标签)的情况下,从任何地方(例如递归循环)中断脚本:

Function Quit($Text) {
    Write-Host "Quiting because: " $Text
    Break Script
}