Fun with Debug Messages

In my script and function development, I often add the line $DebugPreference="SilentlyContinue" to the beginning of my code. Throughout the script I add lines using Write-Debug that tell me what the script is doing or the value of a particular variable. This has been very helpful. When I want to see the debug messages, I set $DebugPreference to "Continue" and voila!.  In PrimalScript all the messages are written to the debug panel.  But I wanted to do more than merely have a line like:

write-debug "creating user account"

I wanted to see more information like a time stamp or user credentials. I also found it difficult sometimes to pass object properties to the debug pipeline. So I came up with a function I call New-DebugMessage.

   1: Function New-DebugMessage {
   2:        Param([string]$text)
   3:        
   4:        # build a text string of information that can be passed
   5:        # to different pipelines like Debug
   6:        
   7:        #here are some variables you might want to work with
   8:        $computer=$env:computername
   9:        $domain=$env:userdomain
  10:        $user=$env:username
  11:        $timestamp=(Get-Date -Format g).toString()
  12:        $line=$($myinvocation.scriptlinenumber)
  13:        $script=$($myinvocation.invocationname)
  14:        
  15:        [string]$msg="[{0}:{1}\{2}] {3} Line:{4} {5}" -f $computer,$domain,$user,$timestamp,$line,$text
  16:        
  17:        write $msg
  18:    
  19:    }
  20:  

The function returns a string that can be used by Write-Debug:

Write-Debug (New-DebugMessage "Getting powershell process")

The string is passed to the function. Within the function I’ve set some variables that you might find handy in your debug message. Most of them should be self-explanatory. The $line variable will display the line number of your script where the Write-Debug message occurs. If you place your Write-Debug command before key commands, it should be easy to jump to those sections.

Here’s a short script that I tested this with.

$debugpreference="continue"

Write-Debug (New-DebugMessage "starting $($myinvocation.invocationname)")
Write-Debug (New-DebugMessage "Getting Date")
Get-Date
Write-Debug (New-DebugMessage "Getting powershell process")
Get-Process powershell
Write-Debug (New-DebugMessage "finished")

When I run the script I get this output (click the image for a larger view):

debug

Does this look useful to you?  What other things would you like to add or did you add to your debug messages?

Download the function here.