150
votes

I am having a little confusion about the various ways to print (echo) to the console. I have seen that there are multiple ways to write output to the console, such as:

Write-Host "Hello world1"
"Hello World2"
Out-Host -InputObject "Hello World3"

All three ways will print to the console. The middle one is somehow simpler and less verbose and easier to use. I also find that when you write a function such as:

function GetValues()
{
    "1"
    "2"
}

It still returns two strings in the pipeline:

And I'm still able to print out the values:

foreach ($s in GetValues)
{
    Write-Host "s: " $s
}

The thing that I have found was that using just the quoted string doesn't always appear on custom hosts, and that I have had to use Write-Host to get values to print on custom hosts.

Somehow I find this confusing. Is "Print something" supposed to be an alias to Write-Host or what is the intent?

2
Does this answer your question? Echo equivalent in PowerShell for script testingTylerH

2 Answers

109
votes

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

61
votes

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something