powershell - 我怎样才能得到一个任务来设置一个可以在配置中使用的变量?

标签 powershell visual-studio-code vscode-tasks

在 VS Code 中,我定义了一个任务:

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

GetCredentials.ps1 创建凭证并将其分配给 $Global:credential。

在 launch.json 中,我想使用 $Global:credential 作为我正在调试的实际脚本的参数:
    "configurations": [
        {
            "type": "PowerShell",
            "request": "launch",
            "name": "Exchange Parameter Set, No Inactive",
            "preLaunchTask": "getcredentials",
            "script": "${file}",
            "args": [ "-Credential $Global:credential"],
            "cwd": "${file}"
        }
]

但是,脚本不会获取 $Global:credential 的值(而是提示输入凭据)。我认为这应该是可能的,因为这 https://code.visualstudio.com/docs/editor/tasks-appendix表示如果未指定环境,则使用父进程环境。

知道我错过了什么,或者这是不可能的吗?

最佳答案

https://code.visualstudio.com/docs/editor/tasks-appendix关于可选 env 的状态键入任务定义:

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

这与环境变量有关,而不是 PowerShell session 。

此外,所引用的父进程环境是 Visual Studio 自己的环境变量块。

换句话说:
  • 由于 PS 任务 session 在 PS 调试 session 开始时已经退出,因此您无法在两个 session 之间传递变量。
  • 即使尝试在您的 PS 任务 session 中设置环境变量也不起作用,因为两个 session 都以 VS Code 作为父进程运行,并且无法看到彼此的环境修改。


  • 最好的办法是使用(临时)文件将值从任务 session 传递到调试 session 。

    this answer了解如何保存到文件和从文件恢复凭据。
    警告:仅适用于 Windows。

    选择任务 session 写入的文件位置(在最简单的情况下具有固定名称,例如 $HOME/.test-creds.clixml ),然后调试 session 从中读取,如下所示:
    "args": [ "-Credential (Import-CliXml $HOME/.test-creds.clixml)" ],
    

    关于powershell - 我怎样才能得到一个任务来设置一个可以在配置中使用的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317136/

    相关文章:

    powershell - 如何以编程方式将Powershell背景色设置为RGB值

    visual-studio-code - 在 Visual Studio Code 中移动 Rust 的下划线位置

    java - VS Code Java 调试器参数

    powershell - 从 url 传递参数运行 PowerShell 脚本

    azure - 通过 Azure DevOps Pipeline 对 Azure DevOps REST API 进行 token 身份验证(而不是 PAT token )

    powershell - 获取内容错误 : "Cannot bind argument to parameter ' Path' because it is null.“

    c++ - 将参数传递给 C++ 程序以在 VSCode 中进行调试

    python - 在 VS Code 中为 python 脚本运行终端?

    visual-studio-code - 如何仅使用task.json链接Visual Studio Code中的任务?

    visual-studio-code - 如何在开始构建时自动清除 VS Code 终端?