There are a number of different ways to output messages. What is the effective difference between outputting something via Write-Host
, Write-Output
, or [console]::WriteLine
?
I also notice that if I use:
write-host "count=" + $count
The +
gets included in the output. Why's that? Shouldn't the expression be evaluated to produce a single concatenated string before it gets written out?
Best Answer
Write-Output
should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it toout-default
if nothing else uses it first.Write-Host
should be used when you want to do the opposite.[console]::WriteLine
is essentially whatWrite-Host
is doing behind the scenes.Run this demonstration code and examine the result.
You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for
Write-Host
, or use string interpolationBTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.