Debugging in PowerShell

The PowerShell integrated scripting environment (ISE) has many of the trappings of a full-fledged programming GUI, including a capability for debugging with breakpoints. There is a TechNet article on debugging from which this discussion is cribbed.  The ISE has a subset of the command-driven breakpoint capability, in that it only allows the setting of line breakpoints. In the command environment, you can also set variable breakpoints, which execute when the value of a variable changes, and command breakpoints, which execute when a certain command is reached.

Breakpoints can only be set for a script that has been saved.

In the ISE window a breakpoint can be set from the debug menu, (Toggle Breakpoint)  or by pressing F9 when the cursor is on the line that you want to use for the breakpoint.  Once set, the line will be highlighted.

After setting a least one breakpoint, you can run the single-stepper. This executes the script one line at time.

Step Into: Executes the current statement and stop at the next statement. If the statement is a function or script, it goes into the function or script and then stops.  F11

Step Over: Execute the current statement and stop at the next statement.  If the statement calls a function or script, it executes the function or script and then returns to the next statement in the original script. F10

Step Out: Executes the current function and then returns to the level above in the call stack. If there are statements remaining in the sub-function, those are executed before the return. Essentially this is something like “finish running this function, and return…”

Continue: Execute to the next breakpoint without single-stepping.

What I’ve been doing as I’ve been learning PowerShell is single stepping through a script, which allows me to look at the effect of a single statement before moving on to the next statement.  This involves setting a breakpoint a the top of the script, and then hitting F11 to toggle through the script.

Calling sub-scripts.

Scripts can be called from other scripts using the Invoke-Expression commandlet.  Example:

Invoke-Expression -Command ./PSFTPDEMO.ps1

If the subscript is located in the current working directory, or within the same directory as the main script, it needs to be prefaced with the ./ path as shown above.

The subscript inherits all variables from the main script unless those variables are declared private in the main script.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s