这个自我回答的问题试图解决在 PowerShell中处理进程退出代码的两个不同方面:
在 PowerShell 代码中,如何查询外部进程设置的退出代码(对外部程序的调用),这些退出代码如何与 PowerShell 的错误处理相结合?
当其他人通过其 CLI pwsh
(PowerShell Core)/ powershell.exe
(Windows PowerShell)调用 PowerShell 时,什么决定了 PowerShell 进程的退出代码,该代码将成功与失败传达给调用进程(可能是构建/CI/自动化服务器任务) ,计划任务或不同的外壳,例如)。
每当启动新的 PowerShell 进程时,Ansgar Wiechers 的答案都很有效。/sf/answers/3514186441/这适用于 cmd.exe 和 powershell.exe。
C:>type .\exit1.ps1
function ExitWithCode($exitcode) {
$host.SetShouldExit($exitcode)
exit $exitcode
}
ExitWithCode 23
Run Code Online (Sandbox Code Playgroud)
在 cmd.exe 交互式 shell 中。
C:>powershell -NoProfile -Command .\exit1.ps1
C:>echo %ERRORLEVEL%
23
C:>powershell -NoProfile -File .\exit1.ps1
C:>echo %ERRORLEVEL%
23
Run Code Online (Sandbox Code Playgroud)
在 PowerShell 交互式 shell 中。
PS C:>powershell -NoProfile -Command .\exit1.ps1
PS C:>$LASTEXITCODE
23
PS C:>powershell -NoProfile -File .\exit1.ps1
PS C:>$LASTEXITCODE
23
Run Code Online (Sandbox Code Playgroud)
但是...在现有交互式 PowerShell 主机内运行 .ps1 脚本将完全退出主机。
PS C:>.\exit1.ps1
<<<poof! gone! outahere!>>>
Run Code Online (Sandbox Code Playgroud)
如何阻止它退出主机 shell?