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.
- 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, 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
- 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.
Second Method
- 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.
Here is the script to test:
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.