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.
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.
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.