windowsvariablesbatch-filescope

How to write a function in batch script that will parse text file to load variable values and return the result to the caller


Per this question:

How to identify the list of unique variable names that are parsed from text file using batch script

I managed to write batch script that will load the variable values and array variable values from a text file by parsing it.

Now, I want to do this in a function or another batch script which will be called by the main script. For example:

:: this is the main Windows Batch Script
call LoadConfigValues.bat
:: display the loaded vales
set

I noticed that since the script being called LoadConfigValues.bat has the statement SETLOCAL ENABLEDELAYEDEXPANSION then all the variables generated by this script will be removed.

How I can force the new variables created by the script LoadConfigValues.bat will be available to the main script?


Solution

  • Solution 1: (the dark one's suggestion)

    setlocal enabledelayedexpansion
    call subroutine
    rem your variables available here
    

    in the subroutine:

    if "" neq "!!" setlocal enabledelayedexpansion
    

    so that the setlocal in the subroutine is only invoked if it it not already in effect (BUT - the variables changed/created would be backed out by the implicit endlocal at the end of the subroutine script).

    Solution 2:

    call subroutine "filename"
    for /f "usebackqdelims=" %%e in ("filename") do set "%%e"
    del "filename"
    

    in the subroutine:

    if "%~1" neq "" for %%e in (%keynameslist%) do set %%e>>"%~1"
    

    to write the variablenames that start with the entries in keynameslist to the file %1 and their values in the format var=value if %1 is specified.

    [both untested]