title: Consuming Powershell stdout with events occurs out-of-order
body: <p>Given a batch script like</p>
  
  <pre><code>@echo off
  for /l %%x in (0, 1, 1000) do echo %%x
  </code></pre>
  
  <p>I'm attempting to run it and capture output to return stdout and stderr over WinRM. The full example is at <a href="https://github.com/puppetlabs/bolt/blob/master/lib/bolt/transport/winrm/connection.rb#L112" rel="nofollow noreferrer">https://github.com/puppetlabs/bolt/blob/master/lib/bolt/transport/winrm/connection.rb#L112</a>.</p>
  
  <p>The short version is</p>
  
  <pre><code>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'
  </code></pre>
  
  <p>When run directly in Powershell (I put it in a .ps1 script and repeatedly invoked it), I occasionally get lines printed out-of-order. An example is</p>
  
  <pre><code>...
  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
  </code></pre>
  
  <p>Any thoughts on what's going wrong? I've reproduced this in Windows Server 2012, Windows 10 Enterprise, and Nano Server.</p>