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, it sends to the host and does not return any objects, it is not possible to export or convert in a specific format. Write-Host has too many limitations.

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

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

Here are few alternatives to Write-Host:

  • Verbose messages: Write-Verbose
  • Warning messages: Write-Warning
  • Error messages: Write-Error
  • Debug messages: Write-Debug

previous-buttonnext-button

3 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

  3. Seguino

    It can be handy for feedback. For example if you want to show the progress when running a long script.
    I finished a script today that shows live patch information and this script collects data from all servers. This can take up to 15 minutes and with write-host I show the user running the script how much % the script is done.

    Reply

Leave a Reply

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