1

This code is being run in pwsh 7, not PowerShell 5 and below.

If I run this code

while ($true) {
    $Read = Read-Host
    $Obj = New-Object Object
    $Obj | Add-Member -MemberType NoteProperty -Name "Text" -Value $Read
    $Obj
}

The first input is ignored, the second input returns both the first and second input at once, and the rest works as intended. How can the first input be returned BEFORE the second input?

This is a simplified version of a bigger project including objects of type System.IO.FileSystemWatcher.

A simple code like

while ($true) {
    $Read = Read-Host
    $Read
}

Works as intended and will return whatever you typed each time you press "enter". This also works with HashTable and more.

  • 2
    Change `$Obj` to `$Obj |Out-Host` – Mathias R. Jessen Aug 14 '23 at 15:12
  • In short: Your output results in implicit `Format-Table` formatting, which incurs a 300-msec. delay before output is rendered (to determine suitable column widths). By contrast, the `Read-Host` prompt prints _right away_, and therefore _before_ your tabular output prints to the display. The - suboptimal - workaround is to force _synchronous_ display output of the tabular data, with `Format-Table` or `Out-Host`. See the linked duplicate for details. – mklement0 Aug 14 '23 at 15:29
  • 1
    @mklement0 Thanks! Had a lot of trouble finding an answer to this! – Samwell9854 Aug 14 '23 at 20:07
  • @mklement0 Actually, I'm trying to reuse the output, but Out-Host throws it to the Information Stream (if I understand) and can't be reused for example in a variable or pipeline. What would be an equivalent of Write-Output but synchronous? There isn't Out-Output, and Out-Default has the same issue as Out-Host. – Samwell9854 Aug 16 '23 at 14:12
  • @Samwell9854, no, `Out-Host` - unlike `Write-Host` - bypasses PowerShell's output streams altogether and prints directly to the host (console). Unfortunately, in order to solve the _display_ problem, you lose pipeline output. But note that it is truly only a _display_ problem - the objects are passed through right away, as the following example shows: `& { while ($true) { $Read = Read-Host; $Obj = New-Object Object; $Obj | Add-Member -MemberType NoteProperty -Name 'Text' -Value $Read; $Obj } } | ForEach-Object { "Text property: $($_.Text)" } ` – mklement0 Aug 16 '23 at 14:23
  • 1
    @mklement0 Omg so my initial code did work, minus the *display* part, and that's where `Out-Host` comes in handy. I was trying to use it in a function which was skipping the first output as per the async delay, and the following `ForEach-Object` - in a terminal - would still not return the first output, UNLESS I add `Out-Host` INSIDE `ForEach-Object {}` - in a terminal. Okay NOW I'm good thx a lot!! *closing 11 browser tabs* – Samwell9854 Aug 16 '23 at 14:56

0 Answers0