Powershell Best Practice #3: Avoid Write-Host

By | May 22, 2015

Best Practice: It is recommended to avoid Write-Host (unless your goal is to write to the host only).

Explanation: Write-Host is like a picture sent to the screen, output to a file is not possible (unless you use Start-Transcript).

Write-Host sends to the host and does not return any objects, it is not possible to export or convert in a specific format, it is limited.
But if Microsoft decided to create this cmdlet, there is a reason.

In some rare cases, you could use Write-Host if you want to display text in a specific colour (ForegroundColor) or with specific background (BackgroundColor) only on the screen (ex: display in colour some specific lines of a log, etc.).

But anyway, Write-Host is not needed msot of the time.

In case you want:

  • Verbose messages: Write-Verbose
  • Warning messages: Write-Warning
  • Error messages: Write-Error
  • Debug messages: Write-Debug
  • Comments describing the goal of the function / script: use Comment-Based Help
  • Comments of lines inside a function / script: use inline comments

An alternative to Write-Host is Write-Output (when you want to send data on the pipeline).
Write-Host writes to the console, Write-Output sends the output to the pipeline.

You could create a function using Write-Host but with the verb “Show”  for example, so we can clearly understand the goal:  Show-Screen

The “Show” verb is defined as: “Makes a resource visible to the user.


previous-buttonnext-button

2 thoughts on “Powershell Best Practice #3: Avoid Write-Host

  1. Pingback: Powershell Best Practice #4: Use CIM cmdlet (not WMI cmdlet) | Powershell Guru

  2. Pingback: Powershell Best Practice #2: Use named parameter (not positional and partial parameter) | Powershell Guru

Leave a Reply

Your email address will not be published. Required fields are marked *