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进程是否是另一个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
希望这会有所帮助。