抛出异常时如何设置退出代码

How to set the exit code when throwing an exception

MyScript.ps1:

exit 1

MyThrow.ps1:

throw "test"

在 PowerShell 中执行:

& ".\MyScript.ps1"
Write-Host $LastExitCode # Outputs 1

Clear-Variable LastExitCode

& ".\MyThrow.ps1"
Write-Host $LastExitCode # Outputs nothing

抛出异常时如何设置正确的退出代码?

你不知道。当您抛出异常时,您希望有人来处理它。有人将是终止执行并设置退出代码的人。例如:

try {
  & ".\MyThrow.ps1"
} catch {
  exit 1
}

如果没有什么可以捕获您的异常,您不应该首先抛出它,而是立即退出(使用正确的退出代码)。

运行 mythrow.ps1 里面的 powershell 会设置 $?为 false,并将添加到 $error 对象数组。 运行 它与另一个 powershell 进程会将 $lastexitcode 设置为 1。

PS C:\> powershell mythrow.ps1
PS C:\> $lastexitcode
1

注意:

Powershell 4 及以下:

抛出异常时,退出代码保持在0(不幸的是)

使用 Powershell 5 及更高版本:

当抛出异常时,退出码默认为1

其实throw也可以设置代码,把它放在throw之前即可。

脚本内容:投掷。ps1

exit 222
throw "test"

输出:

PS C:\> .\Throw.ps1
PS C:\> $LASTEXITCODE
222

如果你运行这样:

powershell .\Throw.ps1

输出结果如下:

PS C:\> powershell .\Throw.ps1
PS C:\> $LASTEXITCODE
1

但事情是这样的,powershell 退出代码应该是 0 或 1, 其他任何东西,最终会给你结果 1.

另一个有趣的事情要提一下,如果要试试 $?在 运行 脚本之后, 如果真或假,结果取决于你想放在那里的东西。 exit 0 --> trueexit 1 --> false

这是一个例子:

脚本内容:Throw_1.ps1

exit 1
throw "test"

输出:

PS C:\> .\Throw_1.ps1
PS C:\> $?
False

脚本内容:Throw_0.ps1

exit 0
throw "test"

输出:

PS C:\> .\Throw_0.ps1
PS C:\> $?
True

如您所见,这正是您需要或想要实现的目标。