我一直在寻找一种方法,在函数中发生不可恢复的错误时终止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).