Powershell Debugging Made Easy: A good start tutorial


There are times when you spot an error yet can’t find where it is located or the lines when it occurred, only then you’ve to go for line-by-line debugging. Powershell has built-in debugging tools for this. Generally, there are 2 methods for debugging. and you can use anything based on your preference.

 

  1. Write-Debug, where you need to manually suspend/continue the running script to inspect.
  2. Set-BreakPoint, which automatically enters into the pre-defined breakpoints, based on Variables or Line number, you defined in the current powershell session.
 
Since I want to show you how to deals with simple debugging methods, let’s start with the simple script. Here, we will add two values 2 and 5. Needlessly to say, the output is 7.  But, it gives out 25 in the result which is unexpected. This is where we should give a try on powershell debugging mode.
 

First Method

  1. You need to define the breakpoints with Write-Debug cmdlet for every line you want to inspect
  2. When you run the script, you need to use -Debug parameter
  3. For every breakpoints, you’ll be asked to:
  • Continue: to continue the script skipping that particular breakpoint
  • Suspend: stops at the breakpoint and inspect the runtime environment
  • Halt: Stop and exit from the script.

Second Method

  1. You need to pre-defined which variable or line number to setup breakpoint and powershell will stops at every these breakpoints, with the current line number & variable.
  2. Those breakpoints go away when you exit from the current powershell session, so it’s session specific. And you can’t save these breakpoints. You turn on breakpoints for every line you want by pressing F9 in powershell ISE.
  3. The command for example isSet-PSBreakpoint -Script myscript.ps1 –Variable x,y,result –Mode ReadWrite
** -Mode Parameter accepts 3 inputs: Read, Write and ReadWrite. Read is used when you want to stops the script when these variables are read. Write for when these variables are being written. And, ReadWrite for both. I explained the debugging steps in the figure for easy viewing. See the script at the end.
 
Powershell Debugging

Fig-1:Method 1

 
Powershell Debugging

Fig-2: Method 2


After you’ve checked the variables, the error is you’ve defined the variables $first and $second as string types. So, just remove it.
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *