Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a task to set a variable that can be used in a configuration?

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?

like image 621
yltlatl Avatar asked Jul 13 '18 03:07

yltlatl


1 Answers

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)" ],
like image 59
mklement0 Avatar answered Sep 30 '22 06:09

mklement0