DEV Community

Cover image for Powershell 7 Debugging Secret
Erick
Erick

Posted on • Originally published at erickguillen.dev

Powershell 7 Debugging Secret

Powershell 7 introduced a new feature that not many people on the internet seem to know yet.
I'm talking about -ErrorAction mode Break

This new error action mode allows you to start a debugging session at the time a script reaches an error. Sounds easy right? Let's try it out!

Disclaimer: I usually haven't use the debugger, I'm one of those that usually start running commands one by one on the console to see where the code breaks 😅. But I think its time to grow up and start debugging like a pro and this new feature makes debugging a lot easier!

First, let's create a function that will have an error which we will need to fix.

function Divide-function{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [int]
        $Number
    )
    process{
        return $Number/0 
    }
}

We will save our function in a Divide-function.ps1 file and open a Powershell session and dot source it . ./Divide-function.ps1

Then we run our function for the first time and let's we what happens

PS> Divide-Function 2
RuntimeException: C:\Scripts\Divide-Function.ps1:9
Line |
   9 |          return $Number/0
     |                 ~~~~~~~~~
     | Attempted to divide by zero.

WOW an ERROR! Now let's try to debug it

PS> Divide-Function 2 -ErrorAction Break
Entering debug mode. Use h or ? for help.

At C:\Scripts\Divide-Function.ps1:9 char:16
+         return $Number/0
+                ~~~~~~~~~

Easy as that, now we are debugging exactly where our code failed!

You can use this opportunity to explore the debugger on your own from here. I advise you to start with the PowerShell advice and use h or ? for help.


 s, stepInto         Single step (step into functions, scripts, etc.)
 v, stepOver         Step to next statement (step over functions, scripts, etc.)
 o, stepOut          Step out of the current function, script, etc.

 c, continue         Continue operation
 q, quit             Stop operation and exit the debugger
 d, detach           Continue operation and detach the debugger.

 k, Get-PSCallStack Display call stack

 l, list             List source code for the current script.
                     Use "list" to start from the current line, "list <m>"
                     to start from line <m>, and "list <m> <n>" to list <n>
                     lines starting from line <m>

 <enter>             Repeat last command if it was stepInto, stepOver or list

Do you want to know more about PowerShell Debugger: about_Debuggers

Top comments (0)