I need a batch script to be invoked as
SetEnvironmentVariableIfNotSet.bat environment_variable_name <value>
from another script or the command line.
I am by no means specialist in Windows batch scripting but by trial and error and piecing different things together, so far I've came up with this:
@setlocal EnableDelayedExpansion
@if "!%1!"=="" (
echo '%1' undefined. Defining with value
echo %2
endlocal DisableDelayedExpansion
goto :define_variable
) else (
echo '%1' already defined with value
echo !%1!
endlocal DisableDelayedExpansion
goto :eof
)
:define_variable
@set "%1=%2"
When called, does what I need:
C:\>call DefEnvVarIfNotDef.bat ASD "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
'ASD' undefined. Defining with value
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
C:\>echo %ASD%
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
Asking here for a better/an optimal solution. This one certainly looks ugly to me.