20

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

2
  • 1
    Write-Host is not for showing complicated objects. That is what Write-Output is supposed to do. Commented Apr 13, 2016 at 2:05
  • 3
    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. Commented Apr 13, 2016 at 10:00

1 Answer 1

45

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

   $files | Format-Table | Out-String | Write-Host
Sign up to request clarification or add additional context in comments.

1 Comment

$files | Format-Table | Out-String | Write-Host also works. Just saving a few characters.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.