BAT文件(批处理)中的嵌套循环返回不需要的结果

时间:2012-08-03 19:29:57

标签: batch-file

我有以下代码。除了几个问题外,它的效果很好。首先,我的“if not blank”检查根本不起作用。第二,在每次迭代期间,它最后一次将servername作为servername和folder传递,我真的不理解......

 SET servers=server01,server02
 SET drive=c
 SET root=program files (x86)\test\
 SET backup=%root%\backup 
 SET folders=folder01\,folder02\file01.txt


 FOR %%b in (%servers%) do (
    FOR %%a in (%folders% %%b) DO (
        if not %%a == "" call :backup %%b %%a
    )
 )


:backup
 SET currentfile="\\%1\%drive%$\%2"
 setlocal
 echo Backing Up %currentfile%
 REM mkdir "\\%1\%drive%$\%backup%"
 REM xcopy /I
 exit /b
 endlocal
 goto :end

输出

1] Backing Up "\\server01\c$\folder01\"
2] Backing Up "\\server01\c$\folder02\file01.txt"
3] Backing Up "\\server01\c$\server01"
4] Backing Up "\\server02\c$\folder01\"
5] Backing Up "\\server02\c$\folder02\file01.txt"
6] Backing Up "\\server02\c$\server02"
7] Backing Up "\\\c$\"

如您所见,不需要第3,6和7行。

1 个答案:

答案 0 :(得分:4)

第3行和第6行是由于内部for循环中的%%b引起的。引发第7行是因为脚本在循环之后没有终止,所以它最后再次运行:backup代码。

以下似乎给出了预期的结果:

@echo off

SET servers=server01,server02
SET drive=c
SET root=program files (x86)\test\
SET backup=%root%\backup 
SET folders=folder01\,folder02\file01.txt


FOR %%b in (%servers%) do (
    FOR %%a in (%folders%) DO (
        rem echo a is %%a
        if not %%a == "" call :backup %%b %%a
    )
)

exit /b


:backup
SET currentfile="\\%1\%drive%$\%2"
setlocal
echo Backing Up %currentfile%
REM mkdir "\\%1\%drive%$\%backup%"
REM xcopy /I
endlocal