As my build scripts keep getting more complicated, I am now in need of a configuration file for each. Furthermore, I have several machines and I need to sometimes change paths around. In other words, I need a local configuration file for each script and for each host I build on.

I will use myScript.bat as the main executable batch, which contains:

@echo off
SETLOCAL EnableExtensions EnableDelayedExpansion
rem ####################################################################################
rem ## Default Configuration
rem ####################################################################################

SET EXTERNAL_VARIABLE_A=This is the default variable A
SET EXTERNAL_VARIABLE_B=This is the default variable B

rem ####################################################################################
rem ## PLEASE DO NOT EDIT BELOW THIS LINE
rem ####################################################################################

rem We load the config file first
call :loadconfig "%~dpn0"

rem we then carry on execution
call :execScript

@exit /B 0

rem ####################################################################################
rem ## Pseudo-function to load config
rem ####################################################################################
:loadconfig
rem set the variable HOSTNAME by executing the command (that's the computer's name)
FOR /F "delims=" %%a IN ('hostname') DO @set HOSTNAME=%%a

rem strip double quotes
set scriptFile=%1
set scriptFile=%scriptFile:"=%

rem We use two files: myScript.conf and myScript.
rem myScript. overrides myScript.conf
rem %~dpn0 is the full file minus the extension.
FOR %%c IN (
	"!scriptFile!.conf"
	"!scriptFile!.!HOSTNAME!"
) DO (
	IF EXIST "%%c" (
		echo Loading local configuration from: %%c
		FOR /F "usebackq delims=" %%v IN (%%c) DO (set %%v)
	)
)

GOTO :eof

rem ####################################################################################

rem Use this pseudo-function to write the code of your main script
:execScript

echo !EXTERNAL_VARIABLE_A!
echo !EXTERNAL_VARIABLE_B!

ENDLOCAL

Then for the configuration file, I will use on my host baux, I will create a file called myScript.baux, which will contain the variables I want to configure externally. Note there is no SET command infront of the variables in the configuration file! The file may look like this:

EXTERNAL_VARIABLE_A=Mary had a little lamb
EXTERNAL_VARIABLE_B=Johny had a little pump

Acknowledgements

Joey, over at StackOverflow, provided the central idea to solving this.

0