Skip to main content

How to Read and Write a Key=Value Configuration File in Batch Script

Hardcoding settings like file paths, server names, or user preferences directly inside a Batch script is a recipe for maintenance headaches. Every time a setting changes, you have to risk breaking the code by editing the .bat file. A better approach is to use an external "Configuration File" (like a .ini or .conf file). Your script reads this file at startup and maps the settings to variables, keeping the logic and the data separate.

This guide will explain how to use the FOR /F command to parse a standard Key=Value configuration file.

1. The Configuration File Format

Create a text file named settings.ini with the following structure. Note that we will support comments starting with a semicolon ;.

; Backup Configuration
SOURCE_DIR=C:\User\Data
BACKUP_DRIVE=D:\Backups
VERBOSE_LOGGING=TRUE
MAX_ATTACHMENTS=5

2. Reading the Config File in Batch

To read this file, we use the FOR /F command. We tell Batch to use the equals sign (=) as a "delimiter," separating the key from its value.

The Loader Script

@echo off
setlocal enabledelayedexpansion

set "ConfigFile=%~dp0settings.ini"

:: Set defaults BEFORE loading the config
:: If a key is missing from the file, these values remain
set "SOURCE_DIR=C:\DefaultSource"
set "BACKUP_DRIVE=D:\DefaultBackup"
set "VERBOSE_LOGGING=FALSE"
set "MAX_ATTACHMENTS=3"

:: 1. Check if config exists
if not exist "%ConfigFile%" (
echo [WARNING] Config file not found: %ConfigFile%
echo Using default values.
goto :StartScript
)

:: 2. Parse the file
:: "usebackq" allows quoted file paths
:: "eol=;" ignores lines starting with a semicolon (comments)
:: "tokens=1,*" grabs the key and everything after the first '='
:: "delims==" sets the equals sign as the split point
for /f "usebackq eol=; tokens=1,* delims==" %%a in ("%ConfigFile%") do (
:: Skip blank lines and lines with empty keys
if not "%%a"=="" (
set "%%a=%%b"
)
)

echo [OK] Configuration loaded from: %ConfigFile%

:StartScript
echo.
echo --- Active Configuration ---
echo Source: !SOURCE_DIR!
echo Target: !BACKUP_DRIVE!
echo Verbose: !VERBOSE_LOGGING!
echo Max Files: !MAX_ATTACHMENTS!
echo -----------------------------
echo.

:: (Your main script logic here)

pause
endlocal

Output:

[OK] Configuration loaded from: C:\Users\David\Desktop\settings.ini

--- Active Configuration ---
Source: C:\User\Data
Target: D:\Backups
Verbose: TRUE
Max Files: 5
-----------------------------

Why this works:

  • tokens=1,*: %%a becomes the "Key" and %%b becomes everything after the first = sign, preserving = characters that may appear in the value.
  • set "%%a=%%b": This line is dynamic. It literally runs set "SOURCE_DIR=C:\User\Data" and so on for every line in the file.
  • eol=;: This allows you to add descriptions or comments to your config file that the script will safely ignore.
  • usebackq: Enables quoting the filename, preventing errors if the config file path contains spaces.

3. Creating/Updating a Config File

You can also use a script to "Save" user preferences back to the disk.

@echo off
setlocal

set "ConfigFile=%~dp0settings.ini"

:: Prompt for values (or use current values as defaults)
set /p "new_source=Enter source path [C:\User\Data]: "
if "%new_source%"=="" set "new_source=C:\User\Data"

set /p "new_backup=Enter backup drive [D:\Backups]: "
if "%new_backup%"=="" set "new_backup=D:\Backups"

:: Write the config file (overwrite with complete structure)
(
echo ; Backup Configuration
echo ; Generated: %date% %time%
echo SOURCE_DIR=%new_source%
echo BACKUP_DRIVE=%new_backup%
echo VERBOSE_LOGGING=TRUE
echo MAX_ATTACHMENTS=5
) > "%ConfigFile%"

echo [OK] Settings saved to: %ConfigFile%

pause
endlocal

How to Avoid Common Errors

Wrong Way: Spaces around the Equals sign

Batch is extremely sensitive to spaces in assignments.

  • KEY = VALUE (with spaces) will create a variable named KEY (with a trailing space) containing VALUE (with a leading space).

Correct Way: Keep your config file clean: KEY=VALUE. No spaces around the = sign.

Problem: Variable Overwriting

If your config file contains a line like PATH=C:\MyTools, you will accidentally overwrite the system's global %PATH% variable, which will break almost every other command in your script.

Best Practice: Prefix your config keys with a specific string to avoid collisions: CFG_SOURCE_DIR, CFG_LOG_PATH, etc.

Problem: Values containing equals signs

If a value contains an = character (such as a connection string), using tokens=1,2 delims== would split the value at the first = in the value itself, truncating it.

Correct Way: Use tokens=1,* instead of tokens=1,2. The * token captures everything after the first delimiter, preserving any = characters within the value.

Best Practices and Rules

1. Default Values

Always set "Default" variables at the top of your script before you run the FOR /F loop (as shown in the Loader Script). This way, if a user deletes a line from the config file, the script doesn't crash from an empty variable.

2. Relative Paths

If your config file is in the same folder as your script, use %~dp0settings.ini to find it (as shown in all examples). This ensures the script works correctly even if it's launched from a different working directory.

3. Case Sensitivity

Keys in FOR /F are case-sensitive. If your config file says Source_Dir=data and your script looks for %SOURCE_DIR%, the variable names won't match. Use consistent capitalization in both the config file and the script.

Conclusions

Externalizing your settings into a Key=Value configuration file is a hallmark of professional software development. By using the FOR /F parser, you make your Batch scripts flexible, easy to maintain, and safer for end-users. Instead of asking users to "Edit the code," you can now simply direct them to the .ini file, a much safer and more professional workflow.