我正在尝试从 PowerShell 运行程序,等待退出,然后访问 ExitCode,但我运气不佳。我不想使用-Wait
with 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 属性?