7

In VS Code I have defined a task:

"tasks": [
    {
        "label": "getcredentials",
        "type": "shell",            
        "command": ".\\TestScripts\\GetCredentials.ps1"
    }
]

GetCredentials.ps1 creates a credential and assigns it to $Global:credential.

In launch.json I want to use $Global:credential as an arg to the actual script I am debugging:

    "configurations": [
        {
            "type": "PowerShell",
            "request": "launch",
            "name": "Exchange Parameter Set, No Inactive",
            "preLaunchTask": "getcredentials",
            "script": "${file}",
            "args": [ "-Credential $Global:credential"],
            "cwd": "${file}"
        }
]

However, the script doesn't get the value of $Global:credential (it instead prompts for credentials). I thought that this should be possible since this https://code.visualstudio.com/docs/editor/tasks-appendix says that the parent process environment is used if no environment is specified.

Any idea what I'm missing, or is this impossible?

Gama11
  • 31,714
  • 9
  • 78
  • 100
yltlatl
  • 73
  • 6
  • 1
    I have very little experience with Visual Studio. Do the individual tasks get launched as individual processes? In that case passing variables between tasks is not going to work, b/c you can't pass (PowerShell) variables across process boundaries. – Ansgar Wiechers Jul 13 '18 at 10:44
  • @Ansgar Wiechers - Will this work if we use BASH on GNU\Linux instead of PowerShell on MS Windows? I'm personally attempting the former and it doesn't seem to be working out for me. – Shawn Eary Sep 14 '21 at 22:13

1 Answers1

1

https://code.visualstudio.com/docs/editor/tasks-appendix states with respect to the optional env key in a task definition:

   /**
     * The environment of the executed program or shell. If omitted
     * the parent process' environment is used.
     */

This relates to environment variables, not PowerShell sessions.

Furthermore, the parent process environment being referred to is Visual Studio's own block of environment variables.

In other words:

  • Since the PS task session has exited by the time the PS debugging session starts, you cannot pass variables between the two sessions.

  • Even attempting to set environment variables in your PS task session won't work, because both sessions are run with VS Code as the parent process and cannot see each other's environment modifications.


Your best bet is to use (temporary) files to communicate values from the task session to the debugging session.

See this answer for how to save to and restore credentials from a file.
Caveat: Works on Windows only.

Choose a file location (in the simplest case with a fixed name, e.g. $HOME/.test-creds.clixml) that the task session writes to, and the debugging session then reads from, along the lines of:

"args": [ "-Credential (Import-CliXml $HOME/.test-creds.clixml)" ],
mklement0
  • 382,024
  • 64
  • 607
  • 775