Search code examples
batch-filedirectoryxcopy

Batch file to copy all contents of folder to another folder based on date


I have multiple auto-generated folders in the location C:\ABC . Each auto-generated folder is created at the start of the day and naming convention is "HS".

Eg:

 - C:\ABC\HS08042015
 - C:\ABC\HS08032015
 - C:\ABC\HS08022015
 - C:\ABC\HS08012015

So if today's date is 08042015, then I want the batch file to copy the previous day's folder (HS08032015) to the new location. So on 08042015, the folder C:\ABC\HS08032015 needs to be copied to another location D:\Reports\HS08032015

As such, this batch file should always copy the previous days, dated folder over to the new location.

I was thinking of using XCOPY, but really could not write a working code.

Any help is highly appreciated. Thanks much.


Solution

  • This uses a script to get yesterdays date in the format you need
    and then uses Robocopy to copy the entire folder tree.

    @echo off
    :: date yesterday or any number
    set day=-1
    echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
    echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
    for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
    del "%temp%\%~n0.vbs"
    set "YYYY=%result:~0,4%"
    set "MM=%result:~4,2%"
    set "DD=%result:~6,2%"
    set "data=%mm%%dd%%yyyy%"
    
    robocopy "C:\ABC\HS%data%" "D:\Reports\HS%data%" /mir
    pause