PowerShell Start-Process 未设置 $lastexitcode [英] PowerShell Start-Process not setting $lastexitcode

查看:54
本文介绍了PowerShell Start-Process 未设置 $lastexitcode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组测试 DLL,我正在通过 Start-Process 命令调用 OpenCover.Console.exe 的 powershell 脚本运行这些 DLL.

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.

我设置了 -returntargetcode 标志

执行后我检查$lastexitcode$?.它们始终分别返回 1 和 True.即使测试失败.

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

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

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

推荐答案

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

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

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

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

当然,这种方法的优点是你不需要等待进程,但稍后当它退出时,你会在 $p 中获得有关它运行的信息.

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.

这篇关于PowerShell Start-Process 未设置 $lastexitcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆