2

I noticed that the following:

Get-ChildItem; Write-Host "-----------";

lists the files first and produces the line afterwards. The same happens when I pipe the object like this:

Get-ChildItem | Select-Object;  Write-Host "---================---"

However, piping with subset of fields changes the displayed order and the line appears above the files listed.

Get-ChildItem | Select-Object Name;  Write-Host "---================---"

How can I explain the phenomenon?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • Are you looking for this: `Get-ChildItem | %{ $_.Name; Write-Host "----========----" }` – SavindraSingh Jun 06 '23 at 07:56
  • 3
    `Format-Table` (indirectly called) can produce out of order output in certain cases, see https://stackoverflow.com/a/43691123/7571258 – zett42 Jun 06 '23 at 07:58
  • @SavindraSingh No. Your sample produces a line under **each** element. I'm trying to get **a single** line below all the names listed. – Konrad Viltersten Jun 06 '23 at 08:05
  • Ohh. I think I misunderstood it. – SavindraSingh Jun 06 '23 at 08:08
  • @zett42 That was it. I'm going to post an answer to my question because I fell that it's more to-the-point'y on my specific issue, while the one you so kindly linked to is a deeper explanations (also a bit harder to google up unless one already knows in what direction it's heading, which to me was rather substantial gotcha). – Konrad Viltersten Jun 06 '23 at 08:31

1 Answers1

0

Based on the comment from @zett42, the error is due unexpected behavior of implicit calls and inner workings of the PowerShell print-outs. The correct approach is to either explicitly state that the output should be piped as a table:

Get-ChildItem | Select-Object Name, Length | Format-Table

or as out channel of the host:

Get-ChildItem | Select-Object Name, Length | Out-Host

Both approaches have drawbacks as discussed in this extensive answer.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438