Verbose and Debug Output in PowerShell

Try to stay away from Write-Host in PowerShell - consider these alternatives to producing debug and verbose output!

Don Jones

December 15, 2011

3 Min Read
ITPro Today logo

 

I'm constantly telling people not to use Write-Host in PowerShell. There are a number of reasons to stay away from it, and really only one reason to use it. That reason: You want to display colored output on the screen and you never want that output to be redirectable to anyplace else. Now, folks will usually push back, and insist that they need to use Write-Host to display two types of output: "Debug output," also called "trace code," and "progress information," such as messages that tell you what the script is attempting to do right then.

 

To both situations, I say no, no, no, no, no. Remember my PowerShell Proverb: Every time you write a script that outputs text, God kills a puppy. It's on your head.

 

Instead, I can get you both of those kinds of output, without using Write-Host, in a much better way.

 

Whether you're writing a script or a function, just add this simply line of code to it. In a script, this'll be the first line of code in the script, after any comments you've added. In a function, it'll be the first line of code inside the function, again after any comment-based help you've added:

 

 

[CmdletBinding()]

 

That's it. Once you do that, your script or function will now pick up two brand-new parameters: -Verbose and -Debug. 

 

Inside your script, use Write-Verbose to output "progress information," such as "connecting to whatever" type statements. Use Write-Debug to display any "trace code," such as dumping the contents of a variable. You'll find that liberal use of Write-Verbose and Write-Debug will also, to a large degree, replace the need for inline comments. I like to have a blank line of text immediately before every Write-Debug or Write-Verbose; it makes my script a bit easier on the eyes.

Related:How To Make PowerShell EXEs Without External Dependencies (Tutorial)

 

By default, neither of these Powershell commands will produce output. To display progress information written by Write-Verbose, run your script or function with the -Verbose switch. Similarly, to turn on debugging, add the -Debug switch. A neat thing about Write-Debug is that it'll pause your script, allowing you to step through major portions of your script, or even suspend your script and check the status of several variables, run test commands, and so forth. Essentially, each Write-Debug becomes a breakpoint, which you can turn on or off by using -Debug or omitting the switch.

 


 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like