PowerShell Start-Process not setting $lastexitcode

放肆的年华 提交于 2021-02-04 15:53:25

问题


I have a set of test DLL's that I'm running from a powershell script that calls OpenCover.Console.exe via the Start-Process command.

I have the -returntargetcode flag set

After execution I check $lastexitcode and $?. They return 1 and True respectively all the time. Even when tests are failing.

Shouldn't $lastexitcode be 0 when all tests pass and 1 when they fail?


回答1:


By default, Start-Process is asynchronous, so it doesn't wait for your process to exit. If you want your command-line tool to run synchronously, drop the Start-Process and invoke the command directly. That's the only way it will set $LASTEXITCODE. For example, causing CMD.exe to exit with a 2:

cmd /c exit 2
$LASTEXITCODE

You can make Start-Process synchronous by adding the -Wait flag, but it still wont' set $LASTEXITCODE. To get the ExitCode from Start-Process you add -PassThru to your Start-Process, which then outputs a [System.Diagnostics.Process] object which you can use to monitor the process, and (eventually) get access to its ExitCode property. Here's an example that should help:

$p = Start-Process "cmd" -ArgumentList "/c exit 2" -PassThru -Wait
$p.ExitCode

Of course the advantage of this approach is you don't need to wait for the process, but later when it exits you have the information about it's run in $p.




回答2:


When executing a GUI application, dropping the Start-Process does not help, as PowerShell does not wait for GUI application to complete, when executing them directly this way. So $LASTEXITCODE is not set.

Piping the (non existing) GUI application output helps, as it makes PowerShell to wait for the application to complete.

notepad.exe | Out-Null
echo $LASTEXITCODE

Note that "GUI application" does not necessarily mean that the application has windows. Whether an application is GUI or console is a flag in .exe file header.


Start-Process -PassThru -Wait as suggested in the answer by @Burt_Harris works too in this case, it's just a bit mode complicated.



来源:https://stackoverflow.com/questions/39496829/powershell-start-process-not-setting-lastexitcode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!