Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display formatted output with Write-Host [duplicate]

Tags:

powershell

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

like image 356
Yucel Avatar asked Apr 12 '16 22:04

Yucel


People also ask

How do I display output in a Table Format in PowerShell?

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.

Should I use write-host?

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.

What does write-HOST command do in PowerShell?

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.


1 Answers

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

 $files | Format-Table | Out-String|% {Write-Host $_}
like image 148
lloyd Avatar answered Nov 12 '22 04:11

lloyd