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:
Then, everytime you change the contents of a variable, add a Write-Debug:
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:
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:
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:
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 - http://windowsitpro.com/go/donjonespowershell!