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 to out-default
if nothing else uses it first.
Write-Host
should be used when you want to do the opposite.
[console]::WriteLine
is essentially what Write-Host
is doing behind the scenes.
Run this demonstration code and examine the result.
function Test-Output {
Write-Output "Hello World"
}
function Test-Output2 {
Write-Host "Hello World" -foreground Green
}
function Receive-Output {
process { Write-Host $_ -foreground Yellow }
}
#Output piped to another function, not displayed in first.
Test-Output | Receive-Output
#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output
#Pipeline sends to Out-Default at the end.
Test-Output
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 interpolation
write-host ("count=" + $count)
# or
write-host "count=$count"
BTW - 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.
Write-Output
when you're emitting results.Write-Host
when you're emitting logging information. Never use[console]::writeline()
. – JohnL[console]::writeline("hello world")
that you can't do withWrite-Host "hello world"
. Another, better, more recently applicable answer is thatwrite-host
wrapswrite-information
so its data gets put on a stream likewrite-error
so you can capture it and use it elsewhere.[console]::writeline()
does not do that – JohnL