Best way to write to console in PowerShell

I have a bit confused about the different printing methods (echo) to the console. I saw that there are several ways to write output to the console, for example:

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

All three methods will print to the console. The mean is something simpler and less detailed and easier to use. I also found that when you write a function like:

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

It still returns two lines in the pipeline:

And I can still print the values:

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

I found that using only the quoted string does not always appear on user hosts and that I had to use Write-Host to get print values ​​on user hosts.

Somehow I find it confusing. Is "Print something" supposed to be a Write-Host alias or what is the purpose?

+83
powershell
May 31 '12 at 10:41
source share
2 answers

The default behavior of PowerShell is simply to discard everything that falls out of the pipeline without being picked up by another element of the pipeline or assigned to a variable (or redirected) to Out-Host . What Out-Host does is obviously host-dependent.

Simply disconnecting from the pipeline does not replace Write-Host , which exists only because text is output to the host application.

If you want output, use the Write-* cmdlets. If you want to return values ​​from a function, then simply drop objects there without a cmdlet.

+62
May 31 '12 at 10:46 a.m.
source share

The average record is written to the pipeline. Write-Host and Out-Host written to the console. "echo" is an alias for Write-Output , which is also written to the pipeline. The best way to write to the console is to use 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 will not work, as Write-Host writes to the console, and not to the pipeline (Do-Something will not receive a line):

 Write-Host "hello world" | Do-Something 
+35
May 31 '12 at 10:55
source share



All Articles