I am very much a novice at Batch Scripting and i'm trying to write a simple script to READ from an INI file based on the Parameters that is passed when the batch file is called.
This is an example for what the INI file would look like:
[SETTING1]
Value1=Key1
Value2=Key2
Value3=Key3
[SETTING2]
Value1=Key1
Value2=Key2
Value3=Key3
[SETTING3]
Value1=Key1
Value2=Key2
Value3=Key3
I am running into a problem when it comes to reading ONLY the section that is called. It will read from any section that matches the "Value" and "Key" and i don't know how to limit it to only read the section with the settings.
The file is being called with this Parameter: run.bat run.ini setting2. My code below is what I have so far and I feel as if i have officially hit a wall. Can anyone help with this? Any help would greatly be appreciated.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET INIFile="%~f1"
for /f "usebackq delims=" %%a in (!INIFile!) do (
if %%a==[%2] (
SET yesMatch=%%a
for /f "tokens=1,2 delims==" %%a in (!yesMatch!) do (
if %%a==Value1 set Key1=%%b
if %%a==Value2 set Key2=%%b
if %%a==Value3 set Key3=%%b
)
ECHO !yesMatch!
ECHO !Key1!
ECHO !Key2!
ECHO !Key3!
pause
)
)
pause
exit /b
Here's a way to get your values.
The data in the file is either
[section]
orname=value
so settlingdelims
to=
will assign either section-only to%%a
or name to%%a
and value to%%b
.The flag is only set (defined) after its appropriate section is encountered, and cleared on the next section. Only of it is defined will the assignment take place.
The advantage of the simple
set %%a=%%b
is that it results in setting whatever values are defined in the section - no changes to the code need to take place if new values are added. Your original version has the advantage of picking particular values and setting only those. You pays your money, you takes your choice.Note that the
/i
switch on anif
statement makes the comparison case-insensitive.Nota also the use of
set "value=string"
which ensures that trailing spaces on a line are not included in the value assigned.edit : By default, the
end of line
character is;
so any line starting;
is ignored byfor/f
. The consequence is that the values for the;-commented-out
section would override the values set for the previous section.Setting
eol
to|
should cure the problem. It really doesn't matter whateol
is set to; it's exactly one character which may not appear anywhere in the INI-file (else that line would appear truncated.)It is possible, if necessary, to set
eol
to control-Z but selecting an unused character is easier...Consequently, a one-line change - the
eol
parameter is included in thefor /f
options.