Theo's answer 向您展示了如何在 Windows 上制作 Visual Studio Code 的默认 shell,Windows PowerShell,创建 BOM-les 的 UTF-8 文件,不幸的是,非常麻烦,因为标准运算符和 cmdlet 不支持它。
在您的情况下,最短的公式是替换:
"command": "gopass \"somekey\" > \"myFile.json\""
与:
"command": "[IO.File]::WriteAllLines(\"$pwd\myFile.json\", (gopass \"somekey\"))"
为了方便将 tasks.json 任务定义为可以使用 > 的未修改 PowerShell 命令字符串,同时还可以生成无 BOM 的 UTF-8 输出,您可以制作您的任务使用 PowerShell Core (v6+) 作为 shell,因为 PowerShell Core 的文件输出 cmdlet 和操作符始终默认为无 BOM 的 UTF8:
先决条件:确保已安装PowerShell Core。
底部展示了如何执行自动按需安装。
注意:最终,PowerShell Core 将与旧版 Windows PowerShell 版本一起预装在 Windows 上,但这 (a) 暂时不会发生,并且 ( b) 没有具体的时间框架。
-
如果您可以全局将 PowerShell Core 替换为 Windows PowerShell - 则无需更改您的任务定义:
注意:这意味着 集成终端 以及 tasks.json 中的所有 "shell" 类型任务将使用 PowerShell Core。
打开setting.json(从命令面板中选择> Preferences: Open Settings (JSON))并添加以下属性:
"terminal.integrated.shell.windows": "pwsh.exe"
注意:如果pwsh.exe 不在您系统的PATH 中,请在"executable" 属性中指定完整 路径;您可以通过打开 PowerShell Core 窗口并执行 (Get-Process -Id $PID).Path 来获取它。
-
如果您想用 PowerShell Core 替换 Windows PowerShell单独任务:
将"option" 对象添加到您的任务定义 JSON 中,使其使用 PowerShell Core 的 CLI 而不是 Windows PowerShell 的:
{
"type": "shell",
"label": "Get data",
"command": "gopass \"somekey\" > \"myFile.json\""
"options": {
"shell": {
"executable": "pwsh.exe",
"args": [ "-noprofile", "-command" ]
}
}
}
在 Windows 上使用自动按需安装 PowerShell Core:
由于执行 PowerShell Core 的自动化用户级安装很容易,您可以完全自动化整个过程,如下所示:
{
"label": "EnsurePsCoreInstalled",
"type": "process",
"command": "powershell.exe",
"args": [
"-noprofile",
"-command",
"if (gcm -ea ignore pwsh) { exit 0 }; Write-Verbose -vb 'Installing PowerShell Core...'; iex \"& { $(irm https://aka.ms/install-powershell.ps1) }\"; $dir = $env:LocalAppData + '\\Microsoft\\PowerShell'; $userPath = [Environment]::GetEnvironmentVariable('Path', 'User') -split ';' -ne ''; if ($dir -notin $userPath) { [Environment]::SetEnvironmentVariable('Path', ($userPath + $dir) -join ';', 'User') }; $env:Path += ';' + $dir; if (gcm -ea ignore pwsh) { Throw 'PowerShell Core was just installed on demand. To make it usable, log off and on again or reboot, or restart Visual Studio Code from a new PowerShell window (run `code`).' } else { Throw 'Installation of PowerShell Core FAILED.' }"
],
"problemMatcher": []
}
- 要让您的
Get Data 任务首先执行任务EnsurePsCoreInstalled,添加以下属性:
"dependsOn": "EnsurePsCoreInstalled"
- 注意:这样做会减慢您的任务,因为任务
EnsurePsCoreInstalled 将首先被调用每次。如果它发现已安装 PowerShell Core 会迅速返回,但运行该任务的 Windows PowerShell 本身具有显着的启动成本。