PowerShell启动过程未设置$ lastexitcode

luc*_*cas 3 powershell

我有一组测试DLL,它们是通过Start-Process命令通过OpenCover.Console.exe的Powershell脚本运行的。

-returntargetcode设置了标志

执行后,我检查$lastexitcode$?。他们一直都分别返回1和True。即使测试失败。

$lastexitcode当所有测试通过时不应该为0,而在所有测试失败时是否应该为1?

Bur*_*ris 6

默认情况下,它Start-Process是异步的,因此它不等待您的进程退出。如果希望命令行工具同步运行,请删除Start-Process并直接调用命令。那是它设置的唯一方法$LASTEXITCODE。例如,导致CMD.exe以2退出:

cmd /c exit 2
$LASTEXITCODE
Run Code Online (Sandbox Code Playgroud)

您可以Start-Process通过添加-Wait标志来使其同步,但仍然不会设置$LASTEXITCODE。要从中获取ExitCode,Start-Process请将其添加-PassThru到中Start-Process,然后输出一个[System.Diagnostics.Process]对象,您可以使用该对象来监视流程,并(最终)访问其ExitCode属性。这是一个应该有所帮助的示例:

$p = Start-Process "cmd" -ArgumentList "/c exit 2" -PassThru -Wait
$p.ExitCode
Run Code Online (Sandbox Code Playgroud)

当然,这种方法的优点是您无需等待该过程,但是稍后退出该过程时,您会获得有关其运行的信息$p