Skip navigation

What To Do / Not to Do in PowerShell: Part 1

This series will touch on a number of best practices around Windows PowerShell, specifically on things that you should (almost) ALWAYS do... and some things you should (almost) NEVER do. Let's kick things off with a "NEVER DO:"

Never use Write-Host.

Write-Host is the only native PowerShell output cmdlet that writes directly to the console window, rather than to a pipeline. By bypassing the pipeline in this fashion, Write-Host seriously limits its functionality - but it also picks up the ability to write text in specified colors. So I'll temper my "never" with this: Only use Write-Host if your goal is to display some kind of colorful splash screen, not unlike the one you get when you open the Exchange Management Shell.

When I teach classes, I like to have my students come up with reasons why they SHOULD use Write-Host... and then, in most cases, tell them what they should be doing instead for those purposes. Here are some examples:

  • I want to display formatted help for a function or script. Use comment-based help instead - run "help about_comment_based_help". PowerShell will format it for you.
  • I want to display step-by-step progress information about what my script is doing. Use Write-Verbose instead. That way, you can easily turn the progress information on and off.
  • I want to display debugging information, like the contents of variables, as my script runs. Use Write-Debug instead. Again, it lets you turn that output on and off as needed.
  • I need to display an error or warning. Write-Error and Write-Warning would be a better way to go in almost all cases. 
  • I just need to display some text! Do you really? PowerShell works better with objects, and that's what your script should be outputting, by means of Write-Output. Let PowerShell's Format cmdlets turn those objects into text like lists and tables. 

So there are a very few instances where Write-Host is the write - er, right - way to go. In most cases, your needs would be better met by another technique or cmdlet. Write-Host is often the go-to cmdlet for folks with extensive VBScript experience, who are used to using WScript.Echo to create script output. That was great for VBScript, because it dealt primarily with text, and didn't have many other options for output. By PowerShell isn't VBScript... so (almost) never use Write-Host!

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish