如何防止退出主机并返回退出代码?

问题描述 投票:2回答:1

aAnsgar Wiechers的答案在启动新的PowerShell进程时效果很好。 https://stackoverflow.com/a/50202663/447901在cmd.exe和powershell.exe中都可以使用。

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

在cmd.exe交互式外壳中。

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

在PowerShell交互式外壳中。

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

但是...在现有的交互式PowerShell主机中运行.ps1脚本将完全退出主机。

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

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

powershell
1个回答
0
投票

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

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

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

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.