PowerShell for Windows Admins

Jun 26 2012   1:50PM GMT

Write-Host Wrong!

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: