The two batch files are executed both by same Windows command processor process and share therefore all environment variables.
Main.bat:
@echo off
set "MyVariable="
call Function.bat hello
echo MyVariable=%MyVariable%
Function.bat:
@echo off
rem Some code ...
set "MyVariable=%~1"
It could be that Function.bat
uses for some reason command SETLOCAL. In this case all environment variables defined as well as all modifications made on environment variables after the command SETLOCAL are lost after corresponding ENDLOCAL. This command is implicitly called by Windows command processor on exiting execution of a batch file for each SETLOCAL not yet completed with explicit execution of corresponding ENDLOCAL. Read this answer for details about the commands SETLOCAL and ENDLOCAL.
It is necessary to explicitly set an environment variable on same command line as the command ENDLOCAL with using immediate environment variable expansion to pass value of an environment variable from current environment variables list to previous environment variables list.
Function.bat:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Some code ...
set "MyVariable=%~1"
endlocal & set "MyVariable=%MyVariable%"
The last command line is preprocessed first by Windows command interpreter to
endlocal & set "MyVariable=hello"
So the command line after preprocessing does not contain anymore any variable reference. The command ENDLOCAL restores previous environment which results in deletion of environment variable MyVariable
. But the second command SET specified on same command line sets this variable once again with the value hello
in restored environment.
See also Single line with multiple commands using Windows batch file.