批处理文件循环不包含嵌套循环

时间:2018-10-24 23:41:13

标签: batch-file cmd

Edit1:

所以看来我的循环运行到最后一条记录,然后执行mkdir和MOVE命令。我觉得我在某处缺少括号吗?

FOR %%i IN (%folderPath%\*.Pdf) DO SET fileName=%%i
  ECHO %fileName%
FOR /f "tokens=3-4 delims=_" %%a IN ("%fileName%") DO SET fileClientID=%%a_%%b
  ECHO %fileClientID%

REM Check to see if folders exist, and if they do not, create them
IF NOT EXIST "%folderPath%\%fileYear%" mkdir %folderPath%\%fileYear%

IF NOT EXIST "%folderPath%\%fileYear%\%fileMonth%" mkdir %folderPath%\%fileYear%\%fileMonth%

IF NOT EXIST "%folderPath%\%fileYear%\%fileMonth%\%fileClientID%" mkdir %folderPath%\%fileYear%\%fileMonth%\%fileClientID%

REM Moves the file from source path to destination path
SET fileSourcePath="%fileName%"
SET fileDestPath="%folderPath%\%fileYear%\%fileMonth%\%fileClientID%"

MOVE "%fileSourcePath%" "%fileDestPath%"

PAUSE

1 个答案:

答案 0 :(得分:0)

所以我终于完成了代码,一切都按预期进行了。我非常感谢大家的帮助,因为这是我编写的第一个批处理文件脚本。下面的最终产品,当然,如果有任何最佳实践或更有效的编写方式,我希望收到反馈。再次感谢!

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

SET folderPath="C:\Users\nha\Desktop\FolderMover\Test"

FOR %%a IN (%folderPath%\*.Pdf) DO (
  SET fileDate=%%~ta
  SET fileName=%%a
FOR /f "tokens=1,3 delims=/, " %%a IN ("!fileDate!") DO (
  SET fileYear=%%b
  SET fileMonth=%%a
For /f "tokens=3-4 delims=_" %%a IN ("!fileName!") DO (
  SET fileClientID=%%a_%%b
IF NOT EXIST !folderPath!\!fileYear!\!fileMonth!\!fileClientID! mkdir !folderPath!\!fileYear!\!fileMonth!\!fileClientID!
  SET fileSourcePath=!fileName!
  SET fileDestPath=!folderPath!\!fileYear!\!fileMonth!\!fileClientID!
  MOVE !fileSourcePath! !fileDestPath!
    )
  )
)