Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug powershell in Visual studio code with parameters from command line

Using Powershell ISE I often set breakpoints in a script and start the script from command line. ISE then stops at the breakpoint and lets me debug from there. How do I do the same from Terminal in Visual Studio Code? Below is a script just to show you what I mean. Starting from a terminal I would write:

.\hello.ps1 -firstName "firstName" -lastName "theLastName"

But doing that from terminal it just starts a new window.

param(
[string]$firstName,
[string]$lastName
)

Write-Host "Starting test script"
try
{
   Write-Host "Hello $firstName $lastName"        
}
catch
{
    Write-Error "Error. Exception: $_"
}

write-host "Script done"
like image 381
pezmannen Avatar asked Jan 24 '17 16:01

pezmannen


People also ask

How do I Debug a PowerShell function in VS Code?

Visual Studio Code Powershell Debugging This debugger can be easily started by pressing F5 when you're in a Powershell script. Stopping execution on a particular line is as easy as setting a breakpoint by clicking next to a line number.

How do you pass command line arguments in Visual Studio code?

To set command-line arguments in Visual Studio, right click on the project name, then go to Properties. In the Properties Pane, go to "Debugging", and in this pane is a line for "Command-line arguments." Add the values you would like to use on this line. They will be passed to the program via the argv array.

How do I Debug a PowerShell script line by line?

To start debuggingPress F5 or, on the toolbar, click the Run Script icon, or on the Debug menu click Run/Continue. The script runs until it encounters the first breakpoint. It pauses operation there and highlights the line on which it paused.


1 Answers

To make the info from Eickhel Mendoza's link explicit - the solution is to set up a Run and Debug config file. This is created in .vscode/launch.json. The content for this case would be:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Hello Script",
            "type": "PowerShell",
            "request": "launch",
            "script": "${workspaceFolder}\\hello.ps1",
            "cwd": "${workspaceFolder}",
            "args": ["-firstName \"firstName\" -lastName \"theLastName\""]
        }
    ]
}

Then just open the "Run and Debug" sidebar pane on VSCode (the play button with the bug or Ctrl+Shift+D), where you can run your launch script and any breakpoints you set will be hit as expected.

like image 60
pjpscriv Avatar answered Sep 16 '22 12:09

pjpscriv