使用 Start-Process 和 WaitForExit 而不是 -Wait 获取 ExitCode [英] Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

查看:57
本文介绍了使用 Start-Process 和 WaitForExit 而不是 -Wait 获取 ExitCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 PowerShell 运行程序,等待退出,然后访问 ExitCode,但我运气不佳.我不想使用 -WaitStart-Process,因为我需要在后台进行一些处理.

I'm trying to run a program from PowerShell, wait for the exit, then get access to the ExitCode, but I am not having much luck. I don't want to use -Wait with Start-Process, as I need some processing to carry on in the background.

这是一个简化的测试脚本:

Here's a simplified test script:

cd "C:\Windows"

# ExitCode is available when using -Wait...
Write-Host "Starting Notepad with -Wait - return code will be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru -Wait)
Write-Host "Process finished with return code: " $process.ExitCode

# ExitCode is not available when waiting separately
Write-Host "Starting Notepad without -Wait - return code will NOT be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru)
$process.WaitForExit()
Write-Host "Process exit code should be here: " $process.ExitCode

运行此脚本将启动记事本.手动关闭后,将打印退出代码,并重新启动,无需使用-wait.退出时不提供 ExitCode:

Running this script will cause Notepad to be started. After this is closed manually, the exit code will be printed, and it will start again, without using -wait. No ExitCode is provided when this is quit:

Starting Notepad with -Wait - return code will be available
Process finished with return code:  0
Starting Notepad without -Wait - return code will NOT be available
Process exit code should be here:

我需要能够在启动程序和等待它退出之间执行额外的处理,所以我不能使用 -Wait.我怎样才能做到这一点,并且仍然可以从此进程访问 .ExitCode 属性?

I need to be able to perform additional processing between starting the program and waiting for it to quit, so I can't make use of -Wait. How can I do this and still have access to the .ExitCode property from this process?

推荐答案

我认为你可以做两件事...

Two things you could do I think...

  1. 手动创建 System.Diagnostics.Process 对象并绕过 Start-Process
  2. 在后台作业中运行可执行文件(仅适用于非交互式进程!)

您可以这样做:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
#Do Other Stuff Here....
$p.WaitForExit()
$p.ExitCode

Start-Job -Name DoSomething -ScriptBlock {
    & ping.exe somehost
    Write-Output $LASTEXITCODE
}
#Do other stuff here
Get-Job -Name DoSomething | Wait-Job | Receive-Job

这篇关于使用 Start-Process 和 WaitForExit 而不是 -Wait 获取 ExitCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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