这个自我回答的问题试图解决在 PowerShell中处理进程退出代码的两个不同方面:
在 PowerShell 代码中,如何查询外部进程设置的退出代码(对外部程序的调用),这些退出代码如何与 PowerShell 的错误处理相结合?
当其他人通过其 CLI pwsh
(PowerShell Core)/ powershell.exe
(Windows PowerShell)调用 PowerShell 时,什么决定了 PowerShell 进程的退出代码,该代码将成功与失败传达给调用进程(可能是构建/CI/自动化服务器任务) ,计划任务或不同的外壳,例如)。
当我尝试“退出”功能时。它不会关闭控制台。它没有任何作用。如何更改它以使其退出控制台?
Write-Host "-------------- MENU ---------------"
Write-Host "Utility Menu"
Write-Host "1 = Help Ipconfig"
Write-Host "2 = Ipconfig"
Write-Host "3 = Notepad"
Write-Host "4 = Calculator"
Write-Host "5 = Exit"
Write-Host "-----------------------------------"
$userinput = Read-Host "Please select a menu item: "
switch ( $userinput )
{
1 {Help Ipconfig}
2 {ipconfig}
3 {start notepad}
4 {start calc.exe}
5 {Exit}
}
Run Code Online (Sandbox Code Playgroud) 我对从cmd.exe调用运行时从PowerShell返回退出代码值有疑问。我发现https://weblogs.asp.net/soever/returning-an-exit-code-from-a-powershell-script有帮助。但是,PowerShell代码的解决方案是添加一个功能。
function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode) exit }
Run Code Online (Sandbox Code Playgroud)
产生:
ExitWithCode : The term 'ExitWithCode' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At C:\src\t\e\exit5.ps1:6 char:1
+ ExitWithCode -exitcode 12345
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (ExitWithCode:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Run Code Online (Sandbox Code Playgroud)
但是,将“出口”放在新行上是可行的。这只是语言异常吗?
function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode)
exit } …
Run Code Online (Sandbox Code Playgroud)