PowerShell tip #1 – Difference between Write-Host and Write-Output

When I started working on PowerShell, I noticed that many people are using two common methods to output strings. One is Write-Host and the other one is Write-Output. I decided to try both of them and noticed no difference…

Pstip1_1

But there is actually a difference. See, the below output:

Pstip1_2

And now this one:

Pstip1_3

What is the difference ?

In the first one you can see that we are directing the output to ‘gm’ (alias for Get-Member cmdlet) and it works. However in the second sample you can see that we are getting an error for  ‘gm’ saying that you must specify and object. This is because we used Write-Host this time.

In short, Write-host just writes whatever it has been asked to write to the console… that’s it. You cannot use it as an input of another command. Whereas Write-Output writes to the pipeline, so the next command can accept it as its input.

A cmdlet like Get-Service is actually equivalent to Get-Service | Write-Output.

Advertisements