cmd.exe - how to get the contents of an environment variable whose name is in another environment variable? [duplicate]

I have a requirement to use nested variables for creating a folder based on a environment variables.

Assume I have variables listed below:

%ABC_ASIA_LOCATION% 
%ABC_EUROPE_LOCATION%
%ABC_US_LOCATION%

and I want to pass the country as variable like %ABC_%COUNTRY%_LOCATION%.

How do I achieve this in Windows utilizing batch scripting?


Solution 1:

you have to enclose each variable into %:

set "ABC=ABC"
set "COUNTRY=EUROPE
set "LOCATION=MUNICH
echo %ABC%_%COUNTRY%_%LOCATION%

Result: ABC_EUROPE_MUNICH

Or if you just want Country as a variable, keeping the rest fixed:

echo ABC_%COUNTRY%_LOCATION

Result: ABC_EUROPE_LOCATION

or if you want the whole thing to be a variable (a variable name containing another variable), you have to use delayed expansion:

setlocal enabledelayedexpansion
set country=EUROPE
set "ABC_EUROPE_LOCATION=a town in southern Germany"
echo !ABC_%country%_LOCATION!

which gives you: a town in southern Germany

Note: setlocal has no effect outside of batchfiles, so delayed expansion works only:
- in batchfiles
- when the command prompt was started with delayed expansion enabled (cmd /v:on) (by default, the command prompt runs with delayed expansion disabled)