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

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

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

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


当前回答

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).

其他回答

当我想让一个函数退出脚本而不抛出错误,但如果从那里使用该函数,则不退出控制台时,我想到了一个简洁的小技巧来做到这一点。它涉及$PSScriptRoot自动变量,该变量仅在运行脚本时定义。

if($PSScriptRoot){exit}

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
} 

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

throw "Error Message"

这将生成一个终止错误。

我认为你在寻找回归而不是打破。Break通常用于循环,并且只从最内部的代码块中中断。使用Return命令退出函数或脚本。