header image

Write-Host Wrong!

Posted by: | June 26, 2012 | No Comment |

Many scripting languages require you explicitly write out to screen – VBScript was an example.

This leads to PowerShell that looks like this

Get-Service |
foreach {
  Write-Host $_.Name, $_.Status

This is bad on so many levels.

Firstly you are doing too much work. Secondly you are emitting text not objects. Thirdly you are doing too much work.

Get-Service |
Format-Table Name, Status –AutoSize

gives a much better result and if you are working at the prompt can be aliased to

gsv | ft Name, Status –a

The last act of the pipeline is to pass the data to Out-Default which performs the screen writing.  Write-Host also passes data to Out-Default which effectively terminates the pipeline.

You should always format the data for display as far into the processing as you possibly can. Once you have called a format cmdlet or Write-Host you have terminated the pipeline.

The best you will get is the text representation that would have been displayed on screen. The worst is garbage output.

So if you want to create a HTML report then

Get-Service |
Select Name, Status |
ConvertTo-Html |
Out-File test.htm

Invoke-Item test.htm

Stick with objects and let the pipeline do the work

under: PowerShell Basics