【发布时间】:2023-04-06 09:03:01
【问题描述】:
Ansgar 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 交互式 shell 中。
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!>>>
如何防止它退出主机外壳?
【问题讨论】:
-
病人:医生,我做“这个”的时候很痛。医生:那就不要做“这个”!!您在问“我怎样才能让灯在关闭时不关闭?”。 :)
exit命令将退出当前的命令解析器。如果您正在运行的主机程序位于顶层,exit命令将关闭该解析器,而没有其他任何东西处于打开状态。我相信答案是,如果您不想让它退出,就不要再告诉它退出了吗? -
顾客:我把这辆车带回来了,因为它不能右转。销售:那就不要右转!!
标签: powershell exit-code