Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Using Write-Debug from Blog Posts - SQLServerCentral

Save for later
  • 2 min read
  • 28 Oct 2020

article-image

I wrote a post about PoSh output recently, noting that in general we ought to use Write-Output or Write-Verbose for messaging. In there, I mentioned Write-Debug as well as a way of allowing the user to control debug information.

Since I often find myself fumbling a bit with debugging scripts, I decided to give this a try and see how it works.

First, let’s build a simple script. In this case, I’ll write a script that takes two parameters and determines which one is larger.

$i = $args[0]
$j = $args[1]
Write-Debug("First Param:$i")
Write-Debug("SecondParam:$j")
if ($i -eq #null ) {   $i = 1
  Write-Debug("Setting first as a default to 1")
}
if ($j -eq #null ) {   $j = 1
  Write-Debug("Setting second as a default to 1")
}
if ($a -gt $b) {   Write-Output("The first parameter is larger")
}
elseif ($i -eq $j ) {   Write-Output("The parameters are equal.")
}
else {       Write-Output("The second parameter is larger")   }

If I run this, I get what I expect. Here are a few executions.

using-write-debug-from-blog-posts-sqlservercentral-img-0

Now, what if I’m unsure of what’s happening. For example, I forget the second parameter. How does my program know the first parameter is larger? I have some debug information in there, but it doesn’t appear. However, if I change the value of $DebugPreference, I see something.

using-write-debug-from-blog-posts-sqlservercentral-img-1

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime

The variable, $DebugPreference, controls how Write-Debug messages are processed. By default, this is set to SilentlyContinue. However, if I change this to Continue, all the messages appear. If I want, I can also set it to Stop or Inquire, allowing me to control the program differently.

You can read more about preference variables here.

This is a handy thing to use. I’ve often had a variable I set in programs, sometimes as a parameter, that allows me to show debug messages, but I often then need a series of IF statements inside code to check this and display debug information. Now, I can just include write-debug info in my code, and if the preference isn’t set, I don’t see them.

I’ve seen this used in custom cmdlets from vendors, including Redgate, and it is nice to be able to access more information when something isn’t working, and have it suppressed by default.

The post Using Write-Debug appeared first on SQLServerCentral.