如何防止主机退出并返回退出代码? [英] How to prevent exit of host and return exit code?

查看:50
本文介绍了如何防止主机退出并返回退出代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ansgar Wiechers 的回答在启动新的 PowerShell 进程时效果很好.https://stackoverflow.com/a/50202663/447901这适用于 cmd.exe 和 powershell.exe.

Ansgar Wiechers' answer works well whenever starting a new PowerShell process. https://stackoverflow.com/a/50202663/447901 This works in both cmd.exe and powershell.exe.

C:>type .\exit1.ps1
function ExitWithCode($exitcode) {
  $host.SetShouldExit($exitcode)
  exit $exitcode
}
ExitWithCode 23

在 cmd.exe 交互式 shell 中.

In a cmd.exe interactive shell.

C:>powershell -NoProfile -Command .\exit1.ps1
C:>echo %ERRORLEVEL%
23
C:>powershell -NoProfile -File .\exit1.ps1
C:>echo %ERRORLEVEL%
23

在 PowerShell 交互式 shell 中.

In a PowerShell interactive shell.

PS C:>powershell -NoProfile -Command .\exit1.ps1
PS C:>$LASTEXITCODE
23
PS C:>powershell -NoProfile -File .\exit1.ps1
PS C:>$LASTEXITCODE
23

然而……在现有交互式 PowerShell 主机中运行 .ps1 脚本将完全退出主机.

HOWEVER... Running the .ps1 script inside an existing interactive PowerShell host will exit the host completely.

PS C:>.\exit1.ps1
    <<<poof! gone! outahere!>>>

如何防止它退出主机外壳?

How can I prevent it from exiting the host shell?

推荐答案

如何防止它退出主机外壳?

How can I prevent it from exiting the host shell?

您可以检查当前运行的 PowerShell 进程是否是另一个 PowerShell 父进程的子进程,并且仅在该条件为真时调用 $host.SetShouldExit().例如:

You can check if the currently running PowerShell process is a child of another PowerShell parent process, and only call $host.SetShouldExit() when that condition is true. For example:

function ExitWithCode($exitcode) {
   # Only exit this host process if it's a child of another PowerShell parent process...
   $parentPID = (Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$PID" | Select-Object -Property ParentProcessId).ParentProcessId
   $parentProcName = (Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$parentPID" | Select-Object -Property Name).Name
   if ('powershell.exe' -eq $parentProcName) { $host.SetShouldExit($exitcode) }

   exit $exitcode
}
ExitWithCode 23

希望这会有所帮助.

这篇关于如何防止主机退出并返回退出代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆