Skip to main content

How to Create an Environment-Specific Configuration Loader in Batch Script

Applications behave differently across environments: development uses local databases and verbose logging, staging mirrors production with test data, and production uses secure connections and minimal logging. An environment-specific configuration loader reads the correct settings for the current environment and exports them as variables that the application or build scripts can consume. This eliminates hardcoded values and ensures consistent, predictable behavior across all deployment targets.

In this guide, we will explore how to build a configuration loader in Batch Script that selects and applies environment-specific settings from configuration files.

Understanding the Pattern

The configuration loader follows a simple pattern:

  1. Determine the current environment (dev, staging, production).
  2. Load a base configuration file with default values.
  3. Override with environment-specific values.
  4. Export variables for use by the application or build system.

Method 1: INI-Style Configuration Files

@echo off
setlocal enabledelayedexpansion

:: Determine environment
if not defined APP_ENV set "APP_ENV=dev"

set "config_dir=config"
set "base_config=%config_dir%\base.cfg"
set "env_config=%config_dir%\%APP_ENV%.cfg"

echo =============================================
echo CONFIGURATION LOADER
echo Environment: %APP_ENV%
echo =============================================
echo.

:: Load base config
if exist "%base_config%" (
echo Loading base config...
for /f "usebackq tokens=1,* delims==" %%K in ("%base_config%") do (
set "key=%%K"
if defined key if not "!key:~0,1!"=="#" (
set "%%K=%%L"
echo %%K=%%L
)
)
) else (
echo [WARNING] Base config not found: %base_config%
)

:: Load environment-specific overrides
if exist "%env_config%" (
echo.
echo Loading %APP_ENV% overrides...
for /f "usebackq tokens=1,* delims==" %%K in ("%env_config%") do (
set "key=%%K"
if defined key if not "!key:~0,1!"=="#" (
set "%%K=%%L"
echo %%K=%%L
)
)
) else (
echo [WARNING] No config file for "%APP_ENV%": %env_config%
)

echo.
echo Configuration loaded.
pause

Example Configuration Files

config/base.cfg:

# Base configuration
APP_NAME=MyWebApp
LOG_LEVEL=info
DB_PORT=1433
MAX_CONNECTIONS=50
ENABLE_CACHE=true

config/dev.cfg:

# Development overrides
DB_SERVER=localhost
DB_NAME=MyApp_Dev
LOG_LEVEL=debug
ENABLE_CACHE=false
API_URL=http://localhost:3000

config/production.cfg:

# Production settings
DB_SERVER=sql-prod-01.company.com
DB_NAME=MyApp_Prod
LOG_LEVEL=warn
MAX_CONNECTIONS=200
API_URL=https://api.myapp.com

Method 2: Reusable Configuration Loader Function

Create a standalone loader script that can be called from any other script:

@echo off
:: load_config.bat - Reusable configuration loader
:: Usage: call load_config.bat [environment]
::
:: Variables are exported to the caller's environment.
:: Example:
:: call load_config.bat production
:: echo %DB_SERVER%

setlocal enabledelayedexpansion

set "env=%~1"
if "%env%"=="" (
if defined APP_ENV (set "env=%APP_ENV%") else (set "env=dev")
)

set "config_dir=%~dp0config"

:: Collect all key=value pairs into a single endlocal export block
set "exports="

:: Load base
if exist "%config_dir%\base.cfg" (
for /f "usebackq tokens=1,* delims==" %%K in ("%config_dir%\base.cfg") do (
set "key=%%K"
if defined key if not "!key:~0,1!"=="#" (
set "exports=!exports! & set "%%K=%%L""
)
)
)

:: Load environment overrides
if exist "%config_dir%\%env%.cfg" (
for /f "usebackq tokens=1,* delims==" %%K in ("%config_dir%\%env%.cfg") do (
set "key=%%K"
if defined key if not "!key:~0,1!"=="#" (
set "exports=!exports! & set "%%K=%%L""
)
)
)

:: Export all collected variables and the environment name to the caller
endlocal %exports% & set "APP_ENV=%env%"

Using the Loader

@echo off
:: Any script can load configuration
call load_config.bat production

echo App: %APP_NAME%
echo Database: %DB_SERVER%\%DB_NAME%
echo Log: %LOG_LEVEL%
echo API: %API_URL%

Method 3: Interactive Environment Selector

@echo off
setlocal enabledelayedexpansion

set "config_dir=config"

echo =============================================
echo ENVIRONMENT SELECTOR
echo =============================================
echo.

if not exist "%config_dir%\" (
echo [ERROR] Config directory not found: %config_dir%
pause
exit /b 1
)

:: List available environments
set "count=0"
echo Available environments:
for %%F in ("%config_dir%\*.cfg") do (
set "fname=%%~nF"
if not "!fname!"=="base" (
set /a count+=1
set "env[!count!]=!fname!"
echo !count!. !fname!
)
)

if !count!==0 (
echo No environment configs found in %config_dir%
pause
exit /b 1
)

echo.
set /p "choice=Select environment: "

:: Validate selection
if !choice! lss 1 (
echo [ERROR] Invalid selection.
pause
exit /b 1
)
if !choice! gtr !count! (
echo [ERROR] Invalid selection.
pause
exit /b 1
)

set "selected=!env[%choice%]!"

echo.
echo Loading !selected! configuration...
echo ====================================

:: Load base
if exist "%config_dir%\base.cfg" (
for /f "usebackq tokens=1,* delims==" %%K in ("%config_dir%\base.cfg") do (
set "key=%%K"
if defined key if not "!key:~0,1!"=="#" set "%%K=%%L"
)
)

:: Load selected environment
for /f "usebackq tokens=1,* delims==" %%K in ("%config_dir%\!selected!.cfg") do (
set "key=%%K"
if defined key if not "!key:~0,1!"=="#" set "%%K=%%L"
)

:: Display loaded configuration
echo.
echo Loaded configuration:
set "APP_ENV=!selected!"
echo APP_ENV=%APP_ENV%
if defined APP_NAME echo APP_NAME=%APP_NAME%
if defined DB_SERVER echo DB_SERVER=%DB_SERVER%
if defined DB_NAME echo DB_NAME=%DB_NAME%
if defined LOG_LEVEL echo LOG_LEVEL=%LOG_LEVEL%
if defined API_URL echo API_URL=%API_URL%

pause

Method 4: JSON Configuration with PowerShell

For more complex configurations, use JSON files parsed by PowerShell:

@echo off
setlocal enabledelayedexpansion

set "env=%APP_ENV%"
if "%env%"=="" set "env=dev"

set "config_file=config\%env%.json"

if not exist "%config_file%" (
echo [ERROR] Config file not found: %config_file%
pause
exit /b 1
)

echo Loading configuration from %config_file%...
echo.

:: Parse JSON and set environment variables
set "load_count=0"
for /f "usebackq tokens=1,* delims==" %%K in (`powershell -NoProfile -Command ^
"$cfg = Get-Content '%config_file%' -Raw | ConvertFrom-Json;" ^
"foreach ($p in $cfg.PSObject.Properties) {" ^
" if ($p.Value -is [string] -or $p.Value -is [int] -or $p.Value -is [bool]) {" ^
" Write-Host ($p.Name + '=' + $p.Value)" ^
" }" ^
"}"`) do (
set "%%K=%%L"
echo %%K=%%L
set /a load_count+=1
)

echo.
if !load_count!==0 (
echo [WARNING] No properties loaded from %config_file%.
) else (
echo Configuration loaded for: %env% (!load_count! properties^)
)

pause

Example JSON Config (config/dev.json)

{
"APP_NAME": "MyWebApp",
"DB_SERVER": "localhost",
"DB_NAME": "MyApp_Dev",
"DB_PORT": "1433",
"LOG_LEVEL": "debug",
"API_URL": "http://localhost:3000",
"ENABLE_CACHE": "false"
}

Method 5: Configuration with Validation

Load and validate that all required settings are present:

@echo off
setlocal enabledelayedexpansion

set "env=%APP_ENV%"
if "%env%"=="" set "env=dev"

:: Required variables
set "required=DB_SERVER DB_NAME APP_NAME LOG_LEVEL API_URL"

echo =============================================
echo CONFIG LOADER WITH VALIDATION
echo Environment: %env%
echo =============================================
echo.

:: Load configs
call :load_file "config\base.cfg"
call :load_file "config\%env%.cfg"

:: Validate required variables
echo Validating...
set "missing=0"
for %%R in (%required%) do (
if not defined %%R (
echo [MISSING] %%R
set /a missing+=1
) else (
echo [OK] %%R=!%%R!
)
)

echo.
if !missing! gtr 0 (
echo [ERROR] !missing! required variable(s^) missing.
exit /b 1
) else (
echo [OK] All required variables set.
)

pause
exit /b 0

:load_file
if exist "%~1" (
for /f "usebackq tokens=1,* delims==" %%K in ("%~1") do (
set "key=%%K"
if defined key if not "!key:~0,1!"=="#" set "%%K=%%L"
)
) else (
echo [WARNING] Config file not found: %~1
)
exit /b 0

Using Configuration in Deployment Scripts

@echo off
:: Deploy script that uses environment configuration

:: Load configuration for target environment
set "APP_ENV=%~1"
if not defined APP_ENV set "APP_ENV=staging"

call load_config.bat %APP_ENV%

echo Deploying %APP_NAME% to %APP_ENV%...
echo Database: %DB_SERVER%\%DB_NAME%
echo API: %API_URL%
echo.

:: Use loaded variables in deployment
dotnet publish MyApp -c Release -o publish ^
/p:DatabaseServer=%DB_SERVER% ^
/p:DatabaseName=%DB_NAME%

robocopy publish "\\%DEPLOY_SERVER%\%DEPLOY_PATH%" /mir /r:3 /w:5 /np

Common Mistakes

The Wrong Way: Hardcoding Environment Values

:: WRONG - Hardcoded for one environment
set "DB_SERVER=localhost"
set "DB_NAME=MyApp_Dev"
set "API_URL=http://localhost:3000"
:: Must edit the script to deploy to staging or production

Output Concern: Hardcoded values require editing the script for each environment, introducing risk of deploying development settings to production. Use configuration files per environment instead.

The Wrong Way: Storing Secrets in Config Files

:: WRONG - Passwords in plain text config files
DB_PASSWORD=SuperSecret123
API_KEY=abc-def-ghi-123

Sensitive values like passwords and API keys should not be stored in configuration files that may be committed to source control. Use environment variables, Windows Credential Manager, or a secrets vault instead.

Best Practices

  1. Use separate files per environment: One config file per environment prevents accidental cross-contamination.
  2. Layer base + overrides: Common defaults in base.cfg, environment specifics in dev.cfg, production.cfg, etc.
  3. Validate required settings: Check that all mandatory variables are defined before proceeding.
  4. Keep secrets out of config files: Use environment variables or secure vaults for passwords and keys.
  5. Comment your configs: Use # prefixed lines to document what each setting controls.

Conclusion

Creating an environment-specific configuration loader in Batch Script follows the layered pattern of loading base defaults then applying environment-specific overrides from dedicated config files. By supporting INI-style and JSON configuration formats, providing interactive environment selection, and validating that all required settings are present, teams eliminate hardcoded values and ensure consistent, predictable application behavior across development, staging, and production environments.