13

I'm little confused about how PowerShell handles the format of the objects when they displayed with Write-Host vs. Write-Output vs. directly calling the object.

I need to use Write-Host, because Write-Output breaks my code when I call it in functions.

But when I used Write-Host, displayed data is not what I expected. I wanted to see my object like in when I directly called it (Write-Host is also the same).

PS> $files = GetChildItem C:\
PS> $files # Or Write-Output $files
PS> Write-Host $files
PS> Write-Host $files |Format-Table
PS> $files | Format-Table | Write-Host

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yucel
  • 2,603
  • 5
  • 28
  • 40
  • 1
    Write-Host is not for showing complicated objects. That is what Write-Output is supposed to do. – Matt Apr 13 '16 at 02:05
  • 1
    Just a correction Matt, Write-Output is for putting an object on the pipeline for consumption by the next function/cmdlet. Only when the end of the pipeline is reached is anything returned to the caller... when called from the PS prompt the Host uses the .ToString() method of the each object returned to display in the console, unless specifically defined this defaults to the object type. – Djarid Apr 13 '16 at 10:00

1 Answers1

39

Out-String will convert the table format to a string. As pointed out by Nick Daniels

 $files | Format-Table | Out-String|% {Write-Host $_}
lloyd
  • 1,683
  • 2
  • 19
  • 23
  • 12
    `$files | Format-Table | Out-String | Write-Host` also works. Just saving a few characters. – Haoshu Mar 28 '19 at 22:22