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-Debug("This is a debug message")
$i = 10
Write-Debug("I: $i")
$i += 1
Write-Debug("I: $i")
$i += 1

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

❯ .\debugscript.ps1

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

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
DEBUG: This is a debug message
DEBUG: I: 10
DEBUG: I: 11

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


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


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.

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.