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.
- Write-Debug, where you need to manually suspend/continue the running script to inspect.
- 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.
- You need to define the breakpoints with Write-Debug cmdlet for every line you want to inspect
- When you run the script, you need to use -Debug parameter
- 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.
- 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.
- 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.
- 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.