I want to create a vscode task that runs when I open a folder with vscode. The task checks for existence of an environment variable. If it exists, then do nothing, but if it does not exist, then the terminal in which the task is running should capture focus to alert the user.
My question is: At the moment the terminal window stays open regardless whether the environment variable exists or not. How can I force the terminal window to only stay open when an error (environment variable does not exist) occurs?
I currently have my task (v2.0.0) defined in .vscode\tasks.json
as:
{
"label": "Check for environment variable",
"type": "shell",
"command": "./check_environment_variable.ps1"
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
"presentation": {
"close": false
}
}
The powershell script is:
# $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
}
I found the following workaround:
"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"
}
In this way the terminal will display its warning message until the user sees it and closes the terminal themselves.
Is there a better way to do it?