Why Doesn't Write-Debug Work? (and what's it for, anyway?)

Just finished talking about Write-Debug to a class, and several students had an "a-ha" moment that I thought I'd share. If you've not used it before, Write-Debug is a great way to add trace code to your scripts. I like to use Write-Debug whenever I access a property or variable, to display the contents of that property or variable. I'll also add a Write-Debug within loops and logic constructs, so that I can see which way each construct is working when the script runs.

Don Jones

October 21, 2010

1 Min Read
ITPro Today logo in a gray background | ITPro Today

Just finished talking about Write-Debug to a class, and several students had an "a-ha" moment that I thought I'd share.

If you've not used it before, Write-Debug is a great way to add trace code to your scripts. I like to use Write-Debug whenever I access a property or variable, to display the contents of that property or variable. I'll also add a Write-Debug within loops and logic constructs, so that I can see which way each construct is working when the script runs.

Problem is, my students pointed out, Write-Debug doesn't produce any output. Go ahead and try it, if you have PowerShell up and running:

Write-Debug "This is a test"
The trick is that debug output is suppressed by default. Just add this to the top of a script to turn debug output on for that script, or run this in the shell to turn debug output on for the entire shell session:

$DebugPreference = "Continue"
Now Write-Debug will work fine. To disable it again, comment out that command in a script, or in the shell set the variable back to its default of "SilentlyContinue". That permits you to leave your Write-Debug statements in place, but simply have them be inactive until you need them again (and no, there's no real performance hit for doing so). Unfortunately, the PowerShell and ISE hosts don't provide a means of redirecting Write-Debug to a file... which is too bad. You could certainly whip up your own "Write-DebugLog" function, though! If you're interested, drop a comment and I'll make it the subject of a future post.

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