我想创建一个 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
}
我找到了以下解决方法:
"presentation": {
"close": false
}
# $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"
}
这样终端将显示警告消息,直到用户看到它并自行关闭终端。
有更好的方法吗?