如何用批处理脚本获取setup.ini指定节下的ProductId值
批处理提取指定节下的ProductId值
以下是直接可用的批处理脚本,专门提取setup.ini中[install.msi]节下的ProductId值,解决你之前遇到的!line!未解析问题:
@echo off setlocal enabledelayedexpansion set "targetSection=[install.msi]" set "inTargetSection=" :: 逐行读取setup.ini for /f "usebackq delims=" %%a in ("setup.ini") do ( set "currentLine=%%a" :: 匹配目标节开头 if "!currentLine!"=="%targetSection%" ( set "inTargetSection=1" goto :continue ) :: 如果已在目标节内,检查是否进入其他节 if defined inTargetSection ( :: 遇到新的节标记,退出目标节 if "!currentLine:~0,1!"=="[" ( set "inTargetSection=" goto :continue ) :: 匹配ProductId行,提取值 if "!currentLine:ProductId=!" neq "!currentLine!" ( for /f "tokens=2 delims==" %%b in ("!currentLine!") do ( set "productId=%%b" :: 移除值前后的空格(如果有) set "productId=!productId: =!" ) echo 目标ProductId: !productId! goto :exitLoop ) ) :continue ) :exitLoop endlocal
关键说明
- 启用延迟扩展:开头的
setlocal enabledelayedexpansion是解决!line!未解析问题的核心——批处理在循环内读取变量时,必须启用延迟扩展才能正确解析!变量名!格式的变量。 - 节范围控制:用
inTargetSection变量标记是否进入目标节,遇到其他节的[xxx]标记时立即退出,确保只读取目标节内的内容。 - 兼容空格情况:脚本用
!currentLine:ProductId=! neq "!currentLine!"判断是否是ProductId行,同时用for /f分割等号提取值,能兼容ProductId={123456}或ProductId = {123456}(等号前后有空格)的情况。
内容的提问来源于stack exchange,提问作者aim0d
相关产品推荐
相关产品推荐

