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

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

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

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


当前回答

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

Get-Help about_trap

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

其他回答

您应该使用exit关键字。

退出也会退出PowerShell。如果你想“打破”当前的函数或脚本-使用break:)

If ($Breakout -eq $true)
{
     Write-Host "Break Out!"
     Break
}
ElseIf ($Breakout -eq $false)
{
     Write-Host "No Breakout for you!"
}
Else
{
    Write-Host "Breakout wasn't defined..."
}

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

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

(环境)::退出(1)

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

我认为你在寻找回归而不是打破。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).