将Powershell stdout与事件一起使用会无序发生

时间:2018-07-18 22:22:12

标签: powershell

给出一个批处理脚本,例如

@echo off
for /l %%x in (0, 1, 1000) do echo %%x

我试图运行它并捕获输出以通过WinRM返回stdout和stderr。完整示例在https://github.com/puppetlabs/bolt/blob/master/lib/bolt/transport/winrm/connection.rb#L112

简称为

function Invoke-Interpreter
{
[CmdletBinding()]
Param (
  [Parameter()]
  [String]
  $Path
)

  $startInfo = New-Object System.Diagnostics.ProcessStartInfo($Path)
  $startInfo.UseShellExecute = $false
  $startInfo.CreateNoWindow = $true
  $startInfo.RedirectStandardOutput = $true

  $stdoutHandler = { if (-not ([String]::IsNullOrEmpty($EventArgs.Data))) { $Host.UI.WriteLine($EventArgs.Data) } }

  $process = New-Object System.Diagnostics.Process
  $process.StartInfo = $startInfo
  $process.EnableRaisingEvents = $true

  $stdoutEvent = Register-ObjectEvent -InputObject $process -EventName 'OutputDataReceived' -Action $stdoutHandler

  [Void] $process.Start()

  $process.BeginOutputReadLine()

  $ret = $process.WaitForExit()
  Unregister-Event -SourceIdentifier $stdoutEvent.Name

  exit $process.ExitCode
}

Invoke-Interpreter './foo.bat'

当直接在Powershell中运行时(我将其放入.ps1脚本中并反复调用它),有时我会无序打印行。一个例子是

...
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
778

对出什么问题有任何想法吗?我已经在Windows Server 2012,Windows 10 Enterprise和Nano Server中复制了此代码。

0 个答案:

没有答案