2
$test_array = @('one', 'two', 'three')

foreach ($entry in $test_array) {
    Write-Host $entry -BackgroundColor Red
    $test = Compare-Object -DifferenceObject $entry -ReferenceObject $entry -IncludeEqual
    $test
}

I have this code above. What I expect is that the result of Compare-Object appears under each entry of the array.

one
InputObject SideIndicator
----------- -------------
one         ==



two
InputObject SideIndicator
----------- -------------
two         ==

three
InputObject SideIndicator
----------- -------------
three       ==

What gets output instead is this:

one

two
three
InputObject SideIndicator
----------- -------------
one         ==
two         ==
three       ==

It skips every entry and outputs the result of everything in the end together. Why does this happen? I'm on Powershell 5.1

David Trevor
  • 794
  • 1
  • 7
  • 22
  • 6
    `$test` -> `$test | Out-Host`. PowerShell does not guarantee output order across streams, so host output usually comes first, since it's written directly to the host console. [Reference](https://blogs.technet.microsoft.com/heyscriptingguy/2014/03/30/understanding-streams-redirection-and-write-host-in-powershell/). – Ansgar Wiechers Oct 07 '19 at 16:34
  • @AnsgarWiechers very insightful link thank you. Also helped me understand what gets returned by functions. Can you post that as an answer? – David Trevor Oct 07 '19 at 18:14
  • 1
    @taclight: Please see the accepted answer to the linked question; specifically, it is _implicit_ `Format-Table` output for types that don't have custom formatting data that is affected, because it is _asynchronous_: it waits for up to 300 msecs. before printing to the console, in an effort to determine suitable column widths. – mklement0 Oct 07 '19 at 19:30
  • @mklement0 thanks for the link. What leaves me wondering however is I added a Start-Sleep for a couple of seconds and it still mashed it together. – David Trevor Oct 07 '19 at 20:05
  • @taclight: `Start-Sleep` blocks all activity in the current thread, so it doesn't solve the problem; the only solution is to _force synchronous output_ by explicitly piping to `Out-Default` / `Out-Host` / `Format-Table`. – mklement0 Oct 07 '19 at 20:22
  • @AnsgarWiechers: `Write-Host` now (PSv5+) writes to the information stream, and - with the very specific exception discussed in the linked post and my other comments here - output across PowerShell streams in the console _is_ in input order. – mklement0 Oct 07 '19 at 20:31

0 Answers0