Function parameters while debugging PowerShell in Visual Studio Code

2 minute read

Visual Studio Code is becoming one of the tools that you need to use when developing PowerShell scripts. It allows you to debug your scripts. But how do you add parameters for debugging. The upcoming paragraphs will explain how.

PowerShell

Parameters are common when developing scripts. Most probably they are configured with the Param object. Just like this example:

Param(
    [String]$ParameterOne,
    [String]$ParameterTwo
)

Write-Output "ParameterOne      :$ParameterOne"
Write-Output "ParameterTwo      :$ParameterTwo"

Running this script called "msftplayground.ps1" within a PowerShell terminal .\msftplayground.ps1will result with no parameters set because they need to be specified.

If you specify the parameters like this .\msftplayground.ps1 -ParameterOne "Test value 1" -ParameterTwo "Test Value 2" those values can then be used during the executing of file.

PowerShell Parameters

Visual Studio Code

With the "Debug" and "Integrated PowerShell Terminal" Visual Studio Code became a real powerfull tool. Debugging sessions can be started by simply pressing "F5".

When you press "F5" within the PowerShell file Visual Studio Code executes the file. So if we for example start the script that we used in this article the following output will be shown

PowerShell Debugging

This is expected behavior because the debugger does not know the parameters that can be used.

So how do you specify the parameters?

Parameters need to be specified within the debugger configuration. Opening the configuration can be done via the debugger bar. Pressing the settings icon will open the configuration.

PowerShell Debugging Bar

The configuration is done in a JSON file called "launch.json". In this file there are configurations for different situations. Choose the correct configuration for your situation and add your parameters in the "args" property.

A single configuration could look like this:

{
   "type": "PowerShell",
   "request": "launch",
   "name": "PowerShell Launch Current File",
   "script": "${file}",
   "args": ["-ParameterOne 'Test value 1'  -ParameterTwo 'Test Value 2'"],
   "cwd": "${file}"
}

Save the configuration and press "F5" to start the debugger. The PowerShell terminal will know show the expected result.