title: Batch script - Set/Define environment variable if not already set/defined
body: <p>I need a batch script to be invoked as</p>
  
  <pre><code>SetEnvironmentVariableIfNotSet.bat environment_variable_name &lt;value&gt;
  </code></pre>
  
  <p>from another script or the command line.</p>
  
  <p>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:</p>
  
  <pre><code>@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"
  </code></pre>
  
  <p>When called, does what I need:</p>
  
  <pre><code>C:\&gt;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:\&gt;echo %ASD%
  "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
  </code></pre>
  
  <p>Asking here for a better/an optimal solution.
  This one certainly looks ugly to me.</p>