3

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.

CristiArg
  • 103
  • 2
  • 7
  • 1
    `if not defined %1 set "%1=%2"`? Just out of curiosity: why do you need something like this? why not simply state `if not defined ASD set ASD="C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"`? – aschipfl Jan 26 '17 at 16:04
  • @aschipfl : the calling script runs in different environments; sometimes the variables exist (fully or incomplete); othertimes none are present; I thought it would be silly to just repeat the `if "ASD"=="" ...`; plus with the scriptlet I get to also ouput what is taken over and what is filled in – CristiArg Jan 27 '17 at 22:23

1 Answers1

5

You could just use If Defined or If Not Defined:

@Echo Off
If "%~1"=="" GoTo :EOF
If Defined %~1 (
    Echo='%~1' already defined with value
    Call Echo=%%%~1%%
    Pause
    GoTo :EOF
)
If "%~2"=="" GoTo :EOF
Echo='%~1' undefined, defining with value
Echo=%~2
Set "%~1=%~2"
Pause
Compo
  • 36,585
  • 5
  • 27
  • 39
  • Thanks for the "%~1" tip. I did not know about it. I needed it to work with: unquoted blanc-less values; quoted blankless value (call with ""blankless-value""); quoted values with blancs in it (MS's silly paths) – CristiArg Jan 27 '17 at 22:00