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:

<pre class="lang-bsh prettyprint prettyprinted">```
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:

<pre class="lang-bsh prettyprint prettyprinted">```
$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.


标签: 进程, exit, your, Process, PowerShell, process, LASTEXITCODE, lastexitcode

相关文章推荐

添加新评论,含*的栏目为必填