Friday, July 22, 2011

Windows XP Batch : reading .ini files

-- settings.ini
; anything after a semi-colon is a comment
; some implementations do not recognize comments, some start them with #
; start a section with a line beginning with a text string inside square brackets
[general] 
key=value  ; data is stored in key/value pairs around an equal sign
; some methods to read INI files require quotes around values with spaces
anotherkey="a value with spaces"
[settings]
force=no
outputlevel=-terse 
 

-- initest.bat
@ECHO OFF
rem %0 is the script file name (with path), %~0 removes the surrounding " " ("%~0" == %0)
rem Adding dp returns the drive and path to the file, instead of the file name itself
set INIFILE="%~dp0settings.ini"
call:getvalue %INIFILE% "outputlevel" "" OUTPUTLEVEL
call:getvalue %INIFILE% "force" "" FORCE
echo outputlevel: %OUTPUTLEVEL%
echo force: %FORCE%
goto:eof
:getvalue
rem This function reads a value from an INI file and stored it in a variable
rem %1 = name of ini file to search in.
rem %2 = search term to look for
rem %3 = group name (not currently used)
rem %4 = variable to place search result
FOR /F "eol=; eol=[ tokens=1,2* delims==" %%i in ('findstr /b /l /i %~2= %1') DO set %~4=%%~j
goto:eof

(Pay special atention to the  @ECHO OFF that the initest.bat file has, because the reference link doesn't have it.)

The result printing is :
outputlevel: -terse
force: no

Reference:

No comments: