powershell - 使用 Start-Process 和 WaitForExit 而不是 -Wait 获取 ExitCode

标签 powershell powershell-2.0

我正在尝试从 PowerShell 运行程序,等待退出,然后访问 ExitCode,但我运气不佳。我不想将 -WaitStart-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

运行此脚本将导致 Notepad即将开始。手动关闭后,会打印退出代码,然后再次启动,无需使用-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 属性?

最佳答案

这里有两件事需要记住。一是添加 -PassThru 参数,二是添加 -Wait 参数。您需要添加等待参数,因为 this defect .

-PassThru [<SwitchParameter>]
    Returns a process object for each process that the cmdlet started. By default,
    this cmdlet does not generate any output.

执行此操作后,进程对象将被传回,您可以查看该对象的 ExitCode 属性。这是一个例子:

$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode

# This will print 1

如果您在没有 -PassThru-Wait 的情况下运行它,它将不会打印任何内容。

同样的答案在这里: How do I run a Windows installer and get a succeed/fail value in PowerShell?

还值得注意的是,上面的“缺陷报告”链接中提到了一种解决方法,如下:

# Start the process with the -PassThru command to be able to access it later
$process = Start-Process 'ping.exe' -WindowStyle Hidden -ArgumentList '-n 1 -w 127.0.0.1' -PassThru

# This will print out False/True depending on if the process has ended yet or not
# Needs to be called for the command below to work correctly
$process.HasExited

# This will print out the actual exit code of the process
$process.GetType().GetField('exitCode', 'NonPublic, Instance').GetValue($process)

关于powershell - 使用 Start-Process 和 WaitForExit 而不是 -Wait 获取 ExitCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262231/

相关文章:

arrays - 在函数中向数组添加元素,但数组仍为空

c# - PowerShell - 如何在运行空间中导入模块

powershell - 开始作业的脚本 block 在 Powershell 中挂起?

c# - 如何让 C# Cmdlet 参数 HelpMessage 显示在 `Get-Help` 中

powershell - 从超过1级深度的属性中从数组中提取项目?

windows - 网络延迟监控脚本窗口

powershell - 强制在 powershell 脚本中立即求值(按值复制变量,而不是引用)

c#-4.0 - C# powershell 输出读取器迭代器在管道关闭和处置时被修改

powershell - 在 PowerShell 中使用双引号

c++ - 通过 Powershell 远程 session 执行时程序输出不同