如何在“ for”命令中循环命令?

时间:2019-04-24 13:24:35

标签: batch-file parameters

我希望批处理文件将文件移动%3次,该怎么办?

%1是源文件夹
%2是目标文件夹
%3是文件数
%4是过滤器。
这是我能想到的最好的方法,但是似乎不能始终如一地工作。

@echo off
SETLOCAL EnableDelayedExpansion
set movedFiles=0
if [%4] EQU [] goto regular
:special
for /R  "%1" %%G in (%4) do (
    echo moving "%4"... "%%G"
    move /Y "%%G" "%2"
    set /a movedFiles+="1"
    if !movedFiles! EQU %3 GOTO endOfCopy
)
GOTO endOfCopy
:regular
for /R  "%1" %%G in (*) do (
    echo moving... "%%G"
    move /Y "%%G" "%2"
    set /a movedFiles+="1"
    if !movedFiles! EQU %3 GOTO endOfCopy
)
:endOfCopy
echo Done, %movedFiles% files Where copied successfully
ENDLOCAL

1 个答案:

答案 0 :(得分:0)

也许您可以稍微更改代码,(同时查看它是否可以解决您的问题)

@Echo Off & SetLocal EnableExtensions DisableDelayedExpansion
If "%~4"=="" (Call :StartMove %* "*") Else Call :StartMove %*
Pause & GoTo :EOF

:StartMove
Set "Moved=0" & For /R "%~1" %%A In ("%~4") Do (SetLocal EnableDelayedExpansion
    If !Moved! Equ %3 (EndLocal & Set "Moved=%Moved%" & GoTo EndMessage)
    Echo ...Moving "%%A" & Move /Y "%%A" "%~2" >Nul 2>&1 && Set /A Moved +=1)

:EndMessage
Echo Done, %Moved% files were copied successfully & EndLocal & Exit /B

请注意,此代码(与您的一样)不会验证输入参数(无论它们是否存在,类型正确,顺序正确等),我建议您实施一些措施,向前迈进。甚至添加如下内容也将是一个开始:

If Not Exist "%~1\" Exit /B
If Not Exist "%~2\" Exit /B
If "%~3"=="" Exit /B