Monday, May 16, 2016

Powershell Debugging Made Easy: A good start tutorial



Scripting is a gift or a painful thing for system admins, it sometimes becomes frustrating when your script encounter errors. 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. Thanks Powershell !
There I found 2 methods for debugging. 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, I’m not going with the complex script and conditional debugging. So, 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.
 Here is the script to test:

  
                                 Figure1: First Method


                              Figure 2: Second Method



After you’ve checked the variables, the error is you’ve defined the variables $first and $second as string types. So, just remove it.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.