按日期复制文件的批处理脚本

时间:2014-08-02 13:21:51

标签: batch-file batch-rename

我需要批处理脚本将今天创建的所有文件从一个目录复制到另一个目录,并将它们全部重命名为默认名称(例如NAME54.pdf)并继续从目标的名称最大数字开始计算。

1 个答案:

答案 0 :(得分:0)

这是一个脚本,它将获取源目标和目标目录,并将文件从源目录复制到目标目录,将脚本重命名为NAMES#.pdf。复制的文件将是具有今天的时间戳

的文件
@echo off
REM setting up variable expansion for later use
setlocal ENABLEDELAYEDEXPANSION

REM giving the inputted values easy to read variable names
SET source_dir=%1
SET dest_dir=%2

REM checks to see if the directories exist
if not exist "%source_dir%" (
    set is_failure=true
)
if not exist "%dest_dir%" (
    set is_failure=true
)

REM Instructions given before failure
if "%is_failure%"=="true" (
    echo ERROR: The parameters passed were not directories\n\n
    echo INSTRUCTIONS
    echo.
    echo command syntax:
    echo script.bat 'path to source directory' 'path to destination directory'
    exit /b 1
)

REM finding the NAME#.pdf files, and getting the highest number
SET i=0
for %%x in (%dest_dir%\NAME*.pdf) do (
  set "FN=%%~nx"
  set "FN=!FN:NAME=!"
  if !FN! GTR !i! set i=!FN!
)

REM checking that the file exists
if exist %dest_dir%\NAME%i%.pdf (
    set /A i=i+1
)

REM Iterating over the list of files, and copying them to the new name
REM Only taking the files with today's date
FOR /F "tokens=1,2,3,4" %%A IN ('"dir %source_dir% /OD /A-D "') DO (
    echo %%A | findstr %DATE%>nul && (
        set file_name=%%D
        copy /Y %source_dir%\!file_name! %dest_dir%\NAME!i!.pdf
        set /A i=i+1
    )
)

这应该完成你需要做的事情