CMD / C launches a new subprocess, which has its own environment space, where the variables are stored in memory. When this process ends, the corresponding environment space is lost, so of course you lose the definition of any variables that were defined there.
A subprocess cannot directly access or manipulate the variables of the parent process.
If you execute a simple command and have control over any output, you can write the definitions to stdout and let FOR / F capture the output so that you can set the values ββin your parent process. But you will need a delayed extension.
Note. This example is pretty inherited, but it should get a point in
for /f "delims=" %%A in ('cmd /v:on /c "set var=hi&echo "var=!var!""') do set %%A
But things can get complicated when deciding what is being cited, what needs to be avoided ...
Life can be simplified if you create a script package that does this work and does it with FOR / F.
test.bat
@echo off set var1=hi set var2=Ain't this fun set var3=bye setlocal enableDelayedExpansion for %%V in (var1 var2 var3) do echo "%%V=!%%V!"
main.bat
@echo off for /f "delims=" %%A in ('cmd /c test.bat') do set %%A
In fact, FOR / F uses implicit CMD / C, and you no longer need to enable slow expansion in a command, so you can disable explicit CMD / C
@echo off for /f "delims=" %%A in ('test.bat') do set %%A
If you do not have control over the output, you will have to write the values ββto a temporary file that the main script can load. You may be tempted to write a temporary batch of script that defines the variables, but then you run the risk of avoiding some characters, depending on the contents of the variables. The safest option is to use the delayed extension to write the names and values ββof the variables and let the parent process use FOR / F to load them.
test2.bat
@echo off set var1=hi set var2=Ain't this fun set var3=bye echo Here is some output that must be preserved, unrelated to variables setlocal enableDelayedExpansion (for %%V in (var1 var2 var3) do echo "%%V=!%%V!") >"%temp%\vars.temp"
main.bat
@echo off setlocal disableDelayedExpansion cmd /c test2.bat call "%temp%\vars.bat" for /f "usebackq delims=" %%V in ("%temp%\vars.temp") do set "%%V" del "%temp%\vars.temp"
Please note that slow expansion must be disabled in the main process when loading variables, otherwise you will lose any characters ! in values ββwith the extension %%V
But to be reliable, you have to do something so that each instance uses a unique temp file name so that simultaneous runs do not thicken with each other.