Skip navigation
PowerShell with a Purpose Blog

A PowerShell Debugging Tip

When you start getting more complicated with PowerShell, and start writing full-on scripts rather than just running commands, you?ll inevitably start writing bugs into your scripts. It?s simple human nature: We are imperfect, and we introduce that imperfection into our scripts.

Once those bugs creep in, there's only one way to get them out: Debugging. The trick with debugging is to understand that a "bug" usually results from a bad expectation on your part. Typically, it's a variable or a property that doesn't contain the value you expected. So to debug, you have to find where reality deviates from your expectation.

One way to do so is to see what's actually contained in those things. Start by adding this to the top of your script:

$DebugPreference = "Continue"

Then, everytime you change the contents of a variable, add a Write-Debug:

Write-Debug "`$var contains $var"

Note the use of double quotes, and note that the first $var has its dollar sign escaped by using the ` backtick character. Do the same thing anytime you have an object property that you rely on:

$wmi = get-wmiobject win32_operatingsystem
write-debug $wmi

Also, use Write-Debug to show the result of any logical decision your script makes. I'll usually make sure I get output no matter which way the decision goes:

If ($wmi.buildnumber -gt 7000) {
    Write-debug "Build is greater than 7000"
} else {
    Write-debug "Build is less than 7000"

All of these debugging statements will help you figure out what values really exist in your script. When you're done debugging, there's no need to remove them: Just suppress them by changing that first line of your script:

$DebugPreference = "SilentlyContinue"

Your debug code will still be in place if you need to modify your script and find that, in doing so, you've introduced another bug. Just turn the debug output back on and hop back into the debugging. 

Extra Tip: Find a scripting editor that directs debug output to a separate pane or window. That's a great way to review the output without it messing up your script's intended output.

Get more Windows PowerShell tips on my new home page -!
Hide 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.