Basics: Debugging 101. Single step through your code and inspect variables

No matter how carefully you lay out your plans and craft your code, you will always find situations where you need to hunt for a bug. It can be a simple logic flaw, an ill-placed copy and paste of code or an edge case you did not think about before.
That is where a debugger comes in. It allows you to designate points in your code where you would like it to stop. Those spots are called breakpoints.
Once your script’s execution is stopped at a breakpoint you can:

– Single step to execute each following statement one-by-one (F10, F11). This allows you to follow your script’s path through the code.
– Examine variables. Sometimes variables have surprising values that throw off the execution of your script. While stopped at breakpoint you can compare your expectation with reality.
– Keep running the script (F5), to see what the next breakpoint is that will cause the execution to stop. Sometimes single stepping is too cumbersome for long loops or larger stretches of code. Place another breakpoint further down and hit F5 to keep your script running.

image

PowerShell Studio and PrimalScript both have a “Run” and a “Debug” option.

image

So you can run your script or you can debug your script. You are able to freely alternate between the two without having to enable or disable breakpoints each time.
Breakpoints are stored between sessions, so you can restart your machine, go for lunch, or continue the next day just as you left off.

SNAGHTML28835e5f

Why, you may ask, is it important to have separate “Run” and “Debug” options?
When you launch a script in a debugger, the engine basically stops at each statement and checks if a breakpoint is hit. If not, it executes the next statement.
You can imagine that this impacts the performance of your script. The timing of when a particular block of code is executed can be essential when testing a script. In a GUI script for example, event handlers won’t get called while you sit at a breakpoint in another event handler.
Jobs you spawned off may finish while your script sits at a breakpoint, so the notification may get lost or the timing is simply off. If you use timers in a GUI script, for example in a progress control, this will quite often just break your script when debugging.
Some modules you use may have multi-threaded code. These could have callbacks or event handlers that can fail when you stop in a debugger. It is also possible that they only fail if you stop at certain points in your code.

So, alternating between debugging and running is essential, especially for larger scripts.

As a general rule, you should debug specific sections of your code to look at the cause of problems. Run your script to test the overall performance and functionality.

Questions about debugging? Please feel free to post them in the comments section.