vscode 任务检查环境变量是否存在

问题描述 投票:0回答:1

我想创建一个 vscode 任务,当我用 vscode 打开文件夹时运行该任务。该任务检查环境变量是否存在。如果存在,则不执行任何操作,但如果不存在,则运行任务的终端应捕获焦点以提醒用户。

我的问题是:目前,无论环境变量是否存在,终端窗口都保持打开状态。如何强制终端窗口仅在发生错误(环境变量不存在)时保持打开状态?

我目前在

.vscode\tasks.json
中将我的任务 (v2.0.0) 定义为:

{
   "label": "Check for environment variable",
   "type": "shell",
   "command": "./check_environment_variable.ps1"
   "problemMatcher": [],
   "runOptions": {
   "runOn": "folderOpen"
   "presentation": {
       "close": false
   }
}

powershell脚本是:

# $environment_variable = $env:USERNAME   # success
$environment_variable = $env:USERNAMEX   # failure
if ([Environment]::GetEnvironmentVariable($environment_variable, 'User')) {
    Write-Host -ForegroundColor green "Environment variable exists: `"$environment_variable`"" 
}else{
    Write-Host -ForegroundColor red "Warning: Environment variable does NOT exist: `"$environment_variable`""
    $missing_variables = $true
}
windows powershell visual-studio-code vscode-tasks
1个回答
0
投票

我找到了以下解决方法:

  1. 设置脚本完成后关闭终端
"presentation": {
   "close": false
}
  1. 如果使用读取提示发生错误,则停止脚本退出:
# $environment_variable = $env:USERNAME   # success
$environment_variable = $env:USERNAMEX   # failure
if ([Environment]::GetEnvironmentVariable($environment_variable, 'User')) {
    Write-Host -ForegroundColor green "Environment variable exists: `"$environment_variable`"" 
}else{
    Write-Host -ForegroundColor red "Warning: Environment variable does NOT exist: `"$environment_variable`""
    Read-Host -Prompt "Press enter to exit"
}

这样终端将显示警告消息,直到用户看到它并自行关闭终端。

有更好的方法吗?

© www.soinside.com 2019 - 2024. All rights reserved.