Best way to write to the console in PowerShell

后端 未结 2 697
刺人心
刺人心 2020-12-13 08:01

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:

相关标签:
2条回答
  • 2020-12-13 08:20

    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.

    0 讨论(0)
  • 2020-12-13 08:39

    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
    
    0 讨论(0)
提交回复
热议问题