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
Using Format-Table for Tabular Output. If you use the Format-Table cmdlet with no property names specified to format the output of the Get-Process command, you get exactly the same output as you do without a Format cmdlet. By default, PowerShell displays Process objects in a tabular format.
In fact its ONLY if you need the richer output for a user interface you should use Write-Host. If you possibly want to write data to the screen, but also want the data to be passed down the pipeline to further commands, then use Write-Output.
Starting in Windows PowerShell 5.0, Write-Host is a wrapper for Write-Information This allows you to use Write-Host to emit output to the information stream. This enables the capture or suppression of data written using Write-Host while preserving backwards compatibility.
Out-String will convert the table format to a string. As pointed out by Nick Daniels
$files | Format-Table | Out-String|% {Write-Host $_}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With