5

I have two batch files. One is the main (caller) file and one is a function. The function takes one parameter, does some stuff and then i wanna return the string to the caller (main.bat). %ERRORLEVEL% is not an option, as it can only return integers.

main.bat:
call function.bat hello
function.bat:
REM some code.......
[HERE THE CODE TO RETURN A STRING TO CALLER FILE]
Seems like a basic operation, so there must be a way. Also, i prefer not making files with the output and reading it in the main.bat, because i want to make it work as a easy-to-use function.

Squashman
  • 13,649
  • 5
  • 27
  • 36

1 Answers1

6

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.

Mofi
  • 46,139
  • 17
  • 80
  • 143