Skip to content

Asynchronous behavior of implicit Format-Table use can have surprising side effects - console output may appear out of order #4594

Closed

Description

A follow-up to #4552.

Reference https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/14925213-bug-console-output-appears-out-of-order

Users have been stumbling over this for a while (see this 2-year-old connect.microsoft.com bug report and various SO questions).

PetSerAl provides an in-depth explanation of the problem in this SO answer.

In short, he states that, starting in PSv5, an implicitly applied Format-Table call now waits 300 ms. before producing output in order to collect a reasonable number of objects to output so as to better determine suitable column widths.

That means that subsequent commands get to execute before the Format-Table output kicks in, which results in surprising behavior if these commands produce non-pipeline display output (e.g., with Write-Host) or prompt for user input, for instance.

Update: A related problem (irrespective of whether the asynchronous output is a problem) is that the implicit output formatting applied to the first command in a script locks in the implicit formatting for all remaining commands, which, if Format-Table is locked in, can lead to objects output by subsequent commands "disappearing", as originally detailed in #4552 (e.g.,
[pscustomobject] @{ one = 1; two = 2}; [pscustomobject] @{ three = 3} makes the 2nd custom object "disappear", because it doesn't share any properties with the 1st one) - see also: #12825

Steps to reproduce

[pscustomobject] @{ one = 1 }  # implicit Format-Table call - in PSv5+, waits 300 ms. before outputting
'hi' | Out-Host # explicit, synchronous, non-pipeline output
Read-Host -Prompt 'Press any key'

Expected behavior

PSv4- produces (note how the implicit Format-Table output comes after the prompt):


one
---
  1
hi
Press any key:

Actual behavior

PSv5+ produces:


hi
Press any key:
one
---
  1

Environment data

PowerShell Core v6.0.0-beta.5 on macOS 10.12.6
PowerShell Core v6.0.0-beta.5 on Ubuntu 16.04.3 LTS
PowerShell Core v6.0.0-beta.5 on Microsoft Windows 10 Pro (64-bit; v10.0.15063)
Windows PowerShell v5.1.15063.483 on Microsoft Windows 10 Pro (64-bit; v10.0.15063)

Activity

  1. SteveL-MSFT commented on Aug 16, 2017

    @SteveL-MSFT
    Member

    The current behavior is by design. If this is a functional issue, I suppose we could have -AutoSize:$false not have the timer

  2. added
    WG-Engine
    on Aug 16, 2017
  3. mklement0 commented on Aug 16, 2017

    @mklement0
    ContributorAuthor

    Steve Lee (@SteveL-MSFT):

    Re as-designed: I assumed as much, but it's another gotcha that calls for Documentation-Needed.

    Re -AutoSize: Note that the problem only occurs with implicit use of Format-Table. If you use ... | Format-Table explicitly - whether with or without -AutoSize - there is no asynchronous behavior.

    Or are we talking about different things?

  4. PetSerAl commented on Aug 16, 2017

    @PetSerAl
    Contributor

    Re -AutoSize: Note that the problem only occurs with implicit use of Format-Table. If you use ... | Format-Table explicitly - whether with or without -AutoSize - there is no asynchronous behavior.

    & {
        [pscustomobject] @{ one = 1 }  # implicit Format-Table call - in PSv5+, waits 300 ms. before outputting
        'hi' | Out-Host # explicit, synchronous, non-pipeline output
        Read-Host -Prompt 'Press any key'
    } | Format-Table
  5. iSazonov commented on Aug 16, 2017

    @iSazonov
    Collaborator

    It seems internally we call Format-Default in the case.

  6. mklement0 commented on Aug 16, 2017

    @mklement0
    ContributorAuthor

    PetSerAl:

    Good point, but what I meant was applying Format-Table directly to the command that would otherwise trigger the asynchronous behavior (under the assumption that that command does not have embedded pipeline-bypassing host operations):

    [pscustomobject] @{ one = 1 } | Format-Table # outputs synchronously
    'hi' | Out-Host # explicit, synchronous, non-pipeline output
    Read-Host -Prompt 'Press any key'

    Now that I think about it, even that use of Format-Table to force synchronous output can be problematic, because - while fine for display - it replaces the original objects with formatting objects in the pipeline.

  7. iSazonov commented on Aug 17, 2017

    @iSazonov
    Collaborator

    It is dup #1747

  8. mklement0 commented on Aug 18, 2017

    @mklement0
    ContributorAuthor

    Ilya (@iSazonov):

    Indeed it is, thanks - due to its generic title, I didn't discover it.

    Given that this issue describes the problem more specifically and includes a command to reproduce it, can I suggest we instead close #1747 as a duplicate?

    Here's its summary:

    Joel Bennett (@Jaykul) states:

    Isn't that the expected result of the delay in Format-Table to get widths for auto-size?
    Do people want to give up that feature to "fix" this oddness in output?

    Steve Lee (@SteveL-MSFT) states:

    This is the side effect of the change we made. Lee Holmes (@LeeHolmes) made the initial change so that we can compute more usable column widths based on objects returned within the first [N units of time].

    Jason Shirk (@lzybkr) states:

    Principle of least surprise - output comes in the order it was written.

    This doesn't mean giving up the feature, it just means flushing what was buffered before writing the other stream.

    Joey Aiello (@joeyaiello) states:

    This is annoying, but I don't think it's a ship blocker.

  9. changed the title [-]Asynchronous behavior of implicit Format-Table use can have surprising side effects[/-] [+]Asynchronous behavior of implicit Format-Table use can have surprising side effects - console output may appear out of order[/+] on Aug 18, 2017
  10. iSazonov commented on Aug 20, 2017

    @iSazonov
    Collaborator
    1. We can check type output object and flush if the type changed.
    2. After ending every pipeline we do some cleanups - at time we can flush the cache too. (We do the same for progress bar hiding.)

    Currently I don't know what way is better.

  11. added this to the milestone on Oct 1, 2017
  12. 18 remaining items

  13. metablaster commented on Dec 19, 2020

    @metablaster

    Since this behavior happens only with [pscustomobject] do you suggest using [psobject] as an alternative since it doesn't have this problem?

    I know psobject is somewhat slower and works slightly differently (ex. doesn't retain the order of members) but I it's still a good workaround, since there is no need to use hackery and should be easy to update existing code that makes use of pscustomobject.

  14. mklement0 commented on Dec 19, 2020

    @mklement0
    ContributorAuthor

    metablaster, the problem isn't specific to [pscustomobject] (which is technically the same as [psobject] - System.Management.Automation.PSObject), it affects all (non-primitive) .NET types that (a) do not have predefined formatting data associated with them and (b) trigger implicit Format-Table formatting due to having 4 or fewer properties; e.g.:

    PS> [regex] ''; write-host hi  # !!  'hi' prints first
    
    hi
    Options RightToLeft MatchTimeout
    ------- ----------- ------------
       None       False -00:00:00.0010000

    As an aside: Use of [psobject] in PowerShell code is best avoided; see this comment for background information on the unfortunate conflation of [psobject] and [pscustomobject].

  15. metablaster commented on Dec 19, 2020

    @metablaster

    Michael Klement (@mklement0)

    I took a look at your link where you said Use [System.Collections.Generic.List[object]], for my specific example in previous duplicate issue #14464 I tried with Dictionary<TKey,TValue> which unfortunately results in same unexpected behavior.

    However your mention of "format data" solved all of my problems and I'm still sticking with PSCustomObject
    I defined Format.ps1xml file with custom type and now all problems are gone 😄

    Thanks so much!

    foreach ($i in 1..3)
    {
    	Write-Information -MessageData "Performing operation $i" -INFA "Continue"
    
    	[PSCustomObject]@{
    		TemplateKey1 = "A$i"
    		TemplateKey2 = "B$i"
    		TemplateKey3 = "C$i"
                    # Cutom type name for Format.ps1xml
    		PSTypeName = "TestType"
    	}
    }

    Actual AND expected behavior

    Performing operation 1
    
    TemplateKey1     TemplateKey2     TemplateKey3
    ------------     ------------     ------------
    A1               B1               C1
    Performing operation 2
    A2               B2               C2
    Performing operation 3
    A3               B3               C3
    
  16. mklement0 commented on Dec 19, 2020

    @mklement0
    ContributorAuthor

    metablaster:

    Glad to hear it. Yes, associating formatting data with any type avoids the problem.

    Re:

    you said Use [System.Collections.Generic.List[object]]

    I should have made it clearer that this was an entirely incidental aspect of why I linked to that comment - I linked to it solely for the background information on [psobject] in the second section.

  17. mklement0 commented on Oct 3, 2021

    @mklement0
    ContributorAuthor

    A more insidious side effect of the asynchronous behavior is that CLI calls from outside PowerShell can result in data loss due to missing output - see this Stack Overflow question and

  18. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  19. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  20. added
    Resolution-No Activity
    on Nov 16, 2023
  21. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  22. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

  23. jszabo98 commented on Nov 24, 2023

    @jszabo98

    Glad to see all these bugs have been resolved.

  24. metablaster commented on Nov 24, 2023

    @metablaster

    Glad to see all these bugs have been resolved.

    lol, reminds me of one reason for not resolving a bug from GNU mailing list labeled as "Nobody cares"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-No ActivityWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions