Blog Post

Setting DebugPreference for Testing–#SQLNewBlogger

,

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

I was working on a PoSh script recently and needed to debug some things. Rather than have Write-Host throughout it, I wanted to log some stuff when I had issues, but not all the time. This post talks about how to do this.

A Simple Script

Here’s a simple script that I wrote to investigate this:

write-host("test")
Write-Debug("This is a debug message")
$i = 10
Write-Debug("I: $i")
$i += 1
Write-Debug("I: $i")
$i += 1
Write-Host($i)

In this script, I have a few messages. If I just run this, I get this result:

? .debugscript.ps1
test
12

That’s pretty easy to see. However, what if I want my debug messages to print? I can add a –Debug parameter, but that doesn’t affect the script.

? .debugscript.ps1 -Debug
test
12

Set $DebugPreference

Instead, what I need to to is change the debug preference, which is in the $DebugPreference variable. This is in the Preference Variable list, and defaults to SilentlyContinue.

However, if I set this to Continue, I get the behavior I want.

? $DebugPreference="Continue"
? .debugscript.ps1
test
DEBUG: This is a debug message
DEBUG: I: 10
DEBUG: I: 11
12

If I don’t want to see these, I can set the variable back.

$DebugPreference="SilentlyContinue"

Using the variable with write-debug is a quick way to turn debugging on and off in your console.

SQLNewBlogger

I had used this before, but had to think about it for a few minutes as I hadn’t done any PowerShell lately. So I decided to add 15 minutes to my work and document this for myself.

And for the next person that wants to interview me on how I write PoSh. You could do the same thing.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating