标题: bat读取ini文件
[打印本页]
作者: blacksheep2000
时间: 2009-11-11 10:01
标题: bat读取ini文件
对chanell编写的脚本进行改良
@echo off
goto start
:usage
@echo :::::::::INI文件读取 :::::::::::::::::::::::::::::::::::::::::::::
@echo ::使用方法: ::
@echo :: inifile iniFilePath [section] [item] [Y] ::
@echo ::例子: ::
@echo :: inifile c:\boot.ini ::
@echo :: 读取c:\boot.ini的所有[section] ::
@echo :: inifile c:\boot.ini "[boot loader]" ::
@echo :: 读取c:\boot.ini [boot loader]段的内容 ::
@echo :: inifile c:\boot.ini "[boot loader]" timeout ::
@echo :: 显示c:\boot.ini [boot loader]段 timeout的值 ::
@echo :: inifile c:\boot.ini "[boot loader]" timeout y ::
@echo :: 设置c:\boot.ini [boot loader]段 timeout为环境变量 ::
@echo :: 返回值:100(文件不存在或未找到) ::
@echo :: 返回值:1(查找的Item不存在) ::
@echo :: 返回值:0(成功) ::
@echo ::::::::::::2009-11-10::::::::::::::::::::::::::::::::::::::::::::
set succ_code=0
goto :eof
:start
set item_value=
set succ_code=1
::对第一个参数进行判断
if "%~1"=="" (
call :usage
goto :exit
)
if "%~1"=="/?" (
call :usage
goto :exit
)
SETLOCAL
set setvar=0
if /i "%~4"=="Y" set setvar=1
::初始化变量
set exit_code=
set item=
set filepath=
set section=
set inifile=
if not "%~1"=="" (
set filepath=%1
) else goto :file_err
if not exist %filepath% goto :file_err
if "%~2"=="" goto :section
set "section=%~2"
set "item=%~3"
if "%item%"=="" set succ_code=0
call :获取数据
endlocal&set "item_value=%item_value%" & set succ_code=%succ_code%
if defined item_value set %item_value%
goto :exit
:获取数据
for /f "usebackq delims=[] skip=2" %%i in (`find /i "%section%" /n %filepath%`) do set 字段开始=%%i
if "%字段开始%"=="" goto :eof
for /f "eol=; usebackq tokens=1,2 skip=%字段开始% delims==;" %%i in (%filepath%) do (
call :分析数据 "%%i" "%%j"
if defined exit_code exit /b %exit_code%&echo exit
)
goto :eof
:分析数据
set a=%~1
set b=%~2
call :trim a
call :trim b
::如果获取到的第一个字符是"[",说明本节已经搜索完成。退出,返回0
if "%a:~0,1%"=="[" (set exit_code=0 & goto :eof )
if not Defined item (
::find items in seciton
echo %a%=%b%
) else (
::find appointed item
if /i "%a%"=="%item%" (
::
set exit_code=0
::find the appointed item success
set succ_code=0
if "%setvar%"=="1" (
::set environment
set item_value="%a%=%b%"
) else (
::show item value
echo %a%=%b%
)
)
)
goto :eof
:section
for /f "eol=; usebackq delims=; skip=2" %%i in (`find /i "[" %filepath%`) do echo %%i
set succ_code=0
goto :exit
:trim
if "!%1:~0,1!"==" " (set %1=!%1:~1!&&goto trim)
if "!%1:~0,1!"==" " (set %1=!%1:~1!&&goto trim)
if "!%1:~-1!"==" " (set %1=!%1:~0,-1!&&goto trim)
if "!%1:~-1!"==" " (set %1=!%1:~0,-1!&&goto trim)
goto :eof
:file_err
echo %1文件未找到或未输入!
exit /b 100
:exit
exit /b %succ_code%