Skip navigation

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.

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.
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