Sometimes when you’re debugging a PowerShell script you may find that you need to run the script in a separate PowerShell instance instead of in the ISE. For example, you may want to test something like transcription which doesn’t work in the ISE. Problem is, when you’re not using the ISE you lose the ability to easily insert a breakpoint into your script and poke around to check whatever it is you want to check. One solution is to write a bunch of lines echoing what each variable is set to at that point. But that’s time consuming, especially if you have a lot of variables you’re interested in. A more efficient solution is to use a very handy method which allows you to temporarily stop a PowerShell script in mid-execution so you can examine those variables dynamically to your heart’s content.
The automatic $host variable has a host (pardon the choice of words) of properties and methods, one of which is EnterNestedPrompt. What this allows you to do is stop script execution at any given point and enter a prompt inside the script with the all the variables available at that point in the script accessible to you. Let’s look at the very simplistic example shown below:
| 001 002 003 004 005 006 007 008 | $a = 1 $b = $a + 1 Write-Host "Entering nested prompt..." $host.EnterNestedPrompt() Write-Host "Out of nested prompt" $c = $b + 1 $c |
All we’re doing here is setting some very basic variables in lines 1 through 4. But the magic happens on line 5 where we enter the nested prompt. Let’s take a look at the script output when this is run:
Notice how after the line “Entering nested prompt” the PS prompt changes from PS C:\Temp> to PS C:\Temp>>. The script is paused at this point and we’re now inside the nested prompt. We can now type anything we want with all the variables active in the script at that time available to us. Notice how I typed $a and $b and got the correct values echoed back. Very handy! Once you’re done, just type exit and the script continues.
No comments:
Post a Comment