Difference between Write-Output and Write-Host in PowerShell

Write-Output and Write-Host both commands can be used to write string text in the PowerShell console. But there are some differences, Write-Host writes the text to the console itself, on the other hand, Write-Output sends the text as an object to the next pipeline command. If no later pipeline command is provided, the Write-Output also outputs the text to the screen.

Example : The following commands return the same output. The Write-Output also prints the text, this is because at the end of every pipeline any remaining data will send to Out-Default which sends to Out-Host.

Write-Host "Text String" //Writes directly to console.
#Text String
Write-Output "Text String" //No next pipeline, send to Out-Default and print
#Text String

If we provide a pipeline command next to Write-Output, then the output will be passed to the next pipeline. In the below example, the output will be passed to the next pipeline and it will be added to the array object. In this case, the Write-Output will not print the text.

$array = @("a", "b", "c")
Write-Output "Text String" | %{$array += $_}
$array

You can also process the output and print using the Select command.

PS C: > Write-Output "SimpleText" | Select @{n='Output';e={'My-Customized-'+ $_}}

Output
------
My-Customized-SimpleText

The Write-Host cmdlet simply writes the given string text, and it will not send the text to the next pipeline command.

PS C: > Write-Host "SimpleText" | Select @{n='Output';e={'My-Customized-'+ $_}}
SimpleText

Another difference is, with the Write-Host command, you can decorate the output with Foreground and Background color, and this is not possible with the Write-Output cmdlet.

Write-Host "Success" -ForegroundColor Green -BackgroundColor Black
Write-Host "Warning" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "Error" -ForegroundColor Red -BackgroundColor Black
Advertisement