Debugging with PowerShell

I see a huge demand for automation even in areas that are not primarily associated with software development or IT in general. And I also see people getting more and more interested in scripting and coding to get annoying, repetitive and boring tasks done more easily and robust. There is only one drawback: Code that automates tasks wants to be written first and debugging is a big aid on the way to get things done. That is why I wrote this text: Because I think PowerShell is a powerful scripting tool and it should not be restricted to software developers only. So let’s get started.

First download and install Visual Studio Code. User Installer with 64 bit is probably the best choice if you are not sure about permissions and architecture. Just make sure to select the following two options during the installation process.

Now create a folder somewhere on your computer. In a workspace, in the documents folder, on your desktop, wherever you will find it again. Make a right click in this folder and choose “Open with Code”.

The next thing that should open right now is the following screen.

Click on the “New File” icon and create a file called “example.ps1”. Open the file and add the following code. You can copy and paste it from here, if you want. The variable in “Round …” is written in this strange way to show you a way of embedding variables in strings. This comes in handy a lot of times and I think it is good to show it right from the start. Don’t forget to save the file.

for ($i = 0; $i -lt 10; $i++) {
	Write-Host -Object "Round $(${i})"
}

If “VS Code” asks you to install the PowerShell extensions, say “Install”. Maybe you have to wait a few moments for everything to load.

Now set a break point on the left side of the code (1). A red dot should appear. Select the “Run and Debug” icon (2) on the left or press “Crtl+Shift+D” on your keyboard. Then choose “Run and Debug” (3) in the sidebar.

Now the PowerShell code should run and stop at the break point:

To continue running the code select (1). To go over the code step by step choose (2). You can inspect the variables used in the code (in this case it is “$i”) on the left side or by hovering with the mouse over it in the code. The console output is on the bottom (4).

Small addition: If you have a big script with a lot of code and you loose track of all your break points, meaning your code stops a lot of time and this gets annoying, you can see a list of breakpoints on the bottom left of the window.

I hope this helps some people. It sure helped me a lot and made my life much easier. Especially when I remember back writing scripts with the old CMD/Batch syntax. This feels like stone age compared to PowerShell 🙂