windows批处理,在嵌套循环中设置变量

时间:2012-12-02 11:40:36

标签: windows loops batch-file command nested

我有以下批处理从文本文件中读取数据,问题出在内部循环中;它应该在目标文件夹中获取lat创建的文件,它什么都没有!

这是我的代码:

:: Delete Files from folder
@echo off
:: Delete Files from folder
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.bak" 
echo Deleting previous bak files...
set destdir=E:\HIS_Data_Consolidation\HIS_Backups
setlocal
FOR /F "tokens=1,2,3 delims=," %%G IN (clinics.txt) DO (
pushd "%%G"
for /F  "tokens=*" %%a in ('dir *.* /b /a-d /o:e 2^>NUL') do (
set lfile=%%a
)
echo copying "%%G\%lfile%" to "%destdir%" ,,,%%H
copy /y "%%G\%lfile%" "%destdir%
E:
cd "%destdir%
E:\HIS_Data_Consolidation\HIS_Backups\unrar.exe e "%destdir%/%lfile%"
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.rar" 
echo Deleting RAR file...
SET v_test=%lfile%
SET v_result=%v_test:rar=bak%
ren "%v_result%"  "%%I"
echo Ready ...
popd
)
pause

感谢您的帮助。 感谢。

2 个答案:

答案 0 :(得分:2)

如果您使用for内部的集合,则需要enabledelayedexpansionhttp://www.robvanderwoude.com/variableexpansion.php

编辑:

:: Delete Files from folder
@echo off
:: Delete Files from folder
echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.bak" 
echo Deleting previous bak files...
set destdir=E:\HIS_Data_Consolidation\HIS_Backups

setlocal enabledelayedexpansion
FOR /F "tokens=1,2,3 delims=," %%G IN (clinics.txt) DO (
    pushd "%%G" 
    for /F  "tokens=*" %%a in ('dir *.* /b /a-d /o:e 2^>NUL') do (
        set lfile=%%a
    )
    echo copying "%%G\!lfile!" to "!destdir!" ,,,%%H
    copy /y "%%G\!lfile!" "!destdir!"
    E:
    cd "!destdir!"
    E:\HIS_Data_Consolidation\HIS_Backups\unrar.exe e "!destdir!/!lfile!"
    echo y | del "E:\HIS_Data_Consolidation\HIS_Backups\*.rar" 
    echo Deleting RAR file...
    SET v_test=!lfile!
    SET v_result=!v_test:rar=bak!
    ren "!v_result!"  "%%I"
    echo Ready ...
    popd
)
endlocal
pause

答案 1 :(得分:0)

@npocmaka 谢谢!你解决了我的问题,我正在工作几个小时! 我有类似的问题。

我使用的是嵌套for循环,并试图将for循环拆分为另一个批处理文件,但是没有用。所以我使用'npocmaka的建议:

这是被调用的批处理,它在另一个for循环中。

@ECHO OFF


SET dir=%~1
SET suf=%~2

ECHO IN dir:%dir%
ECHO IN suf:%suf%
PAUSE

SET /A count=1

SETLOCAL EnableDelayedExpansion
pushd %dir%
FOR /R . %%A IN (*.%suf%) DO (

    ECHO File: %%~nxA count:!count!
    PAUSE
    REN %%~nxA !count!.txt
    CALL :increment RESULT count
)
popd
ENDLOCAL


:increment
SET /A count+=1