Verbose and Debug Output in PowerShell
Try to stay away from Write-Host - consider these alternatives to producing debug and verbose output!
December 15, 2011
I'm constantly telling people not to use Write-Host. There are a number of reasons to stay away from it, and really only one resin 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.
By default, neither of these 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.
Want to ask a question about this article? I'll answer at http://powershell.com/cs/forums/230.aspx!
About the Author
You May Also Like