bat文件如何仅当资源文件修改时调用resgen及正确获取数组值
批处理遍历自定义伪数组取值的正确语法
批处理没有原生数组结构,你定义的obj[n].xxx属于自定义伪数组结构,要在for循环中动态取下标对应的元素,核心要解决两个问题:
- 批处理默认对括号包裹的代码块做预变量展开,代码块内动态赋值、动态生成变量名的内容,用
%变量名%语法无法获取到实时值 - 动态拼接的变量名需要触发二次解析才能拿到对应的值
推荐方案:使用延迟变量扩展
这是最稳定的写法,首先在脚本开头开启延迟扩展,用!变量名!语法取实时值,同时修复了你原脚本中标签放在循环内破坏遍历逻辑的问题,完整修改后代码如下:
@echo on setlocal enabledelayedexpansion echo ------------------------------ echo -- Starting a run of resgen -- echo ------------------------------ Set resourcesPath=%~1Resources\ Set configuration=%~2 Set platform=%~3 set landingPath=%~1bin\%configuration%\Resources\ echo %landingPath% IF exist %landingPath% ( echo %landingPath% exists ) ELSE ( mkdir %landingPath% && echo %landingPath% created) set obj[0].Resource="%landingPath%Strings.en-GB.resources" set obj[0].Text="%resourcesPath%Strings.en-GB.txt" set obj[1].Resource="%landingPath%Strings.ru-RU.resources" set obj[1].Text="%resourcesPath%Strings.ru-RU.txt" set obj[2].Resource="%landingPath%Strings.es-ES.resources" set obj[2].Text="%resourcesPath%Strings.es-ES.txt" FOR /L %%i IN (0 1 2) DO ( rem 动态拼接变量名,用延迟扩展取值 set "textPath=!obj[%%i].Text!" set "resPath=!obj[%%i].Resource!" for %%x in ("!textPath!") do set "date_of_filenameTxt=%%~tx" for %%x in ("!resPath!") do set "date_of_filenameRes=%%~tx" ECHO !date_of_filenameTxt:~0, 16! ECHO !date_of_filenameRes:~0, 16! rem 直接在循环内做判断,避免用内部标签打断循环 IF "!date_of_filenameTxt:~0, 16!" == "!date_of_filenameRes:~0, 16!" ( ECHO No Copy for the : !textPath! ) ELSE ( "%resourcesPath%resgen.exe" !textPath! !resPath! ) ) endlocal
替代方案:用call触发二次解析
如果你不想开启延迟扩展,也可以用call触发二次解析实现取值,写法如下:
@echo on echo ------------------------------ echo -- Starting a run of resgen -- echo ------------------------------ Set resourcesPath=%~1Resources\ Set configuration=%~2 Set platform=%~3 set landingPath=%~1bin\%configuration%\Resources\ echo %landingPath% IF exist %landingPath% ( echo %landingPath% exists ) ELSE ( mkdir %landingPath% && echo %landingPath% created) set obj[0].Resource="%landingPath%Strings.en-GB.resources" set obj[0].Text="%resourcesPath%Strings.en-GB.txt" set obj[1].Resource="%landingPath%Strings.ru-RU.resources" set obj[1].Text="%resourcesPath%Strings.ru-RU.txt" set obj[2].Resource="%landingPath%Strings.es-ES.resources" set obj[2].Text="%resourcesPath%Strings.es-ES.txt" FOR /L %%i IN (0 1 2) DO ( rem 用call二次解析获取动态变量值 call set "textPath=%%obj[%%i].Text%%" call set "resPath=%%obj[%%i].Resource%%" for %%x in ("%textPath%") do set "date_of_filenameTxt=%%~tx" for %%x in ("%resPath%") do set "date_of_filenameRes=%%~tx" call ECHO %%date_of_filenameTxt:~0, 16%% call ECHO %%date_of_filenameRes:~0, 16%% call IF "%%date_of_filenameTxt:~0, 16%%" == "%%date_of_filenameRes:~0, 16%%" ( call ECHO No Copy for the : %%textPath%% ) ELSE ( "%resourcesPath%resgen.exe" %%textPath%% %%resPath%% ) )
注意事项
不要把跳转标签:xxx写在for循环的括号内部,会直接打断for循环的执行逻辑,导致遍历异常,直接把判断逻辑写在循环内即可。
内容的提问来源于stack exchange,提问作者Diego
相关产品推荐
相关产品推荐

