我正在尝试从PowerShell运行程序,等待退出,然后获得对ExitCode的访问权限,但运气不佳。我不希望使用-Wait
与Start-Process
,因为我需要一些处理在后台进行。
这是一个简化的测试脚本:
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:
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属性?