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

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

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

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


当前回答

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

其他回答

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

终止此进程并为底层操作系统提供指定的退出码。

https://msdn.microsoft.com/en-us/library/system.environment.exit%28v=vs.110%29.aspx

(环境)::退出(1)

这将允许您使用特定的退出代码退出,该退出代码可以从调用者那里获得。

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

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

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

throw "Error Message"

这将生成一个终止错误。

我用它来重播一个节目。我不知道它是否有帮助,但它是一个简单的if语句,只需要两个不同的条目。它在powershell中为我工作。

$rerun = Read-Host "Rerun report (y/n)?"

if($rerun -eq "y") { Show-MemoryReport }
if($rerun -eq "n") { Exit }

不知道这是否有帮助,但我相信这将沿线终止程序后,你已经运行它。但是,在这种情况下,每个定义的输入都需要一个列出并分类的输出。您还可以让退出调用显示一个新的提示行,并以这种方式终止程序。