Link to home
Start Free TrialLog in
Avatar of Andreamary

asked on

Write batch file that creates a destination folder with current date and copies files from one network drive folder to another

I would like to create a batch file to use in Windows 10 Task Scheduler for the purpose of doing a daily backup of spreadsheets from one network drive folder to another network folder. I would like the batch file to include the step of creating a sub-folder in the destination 'CAP Spreadsheet Backups' folder, named with the current date (YYYY - MMM- DD), where the spreadsheets would be backed up to.

I have created the copy action:

Copy "\\\productiongraphics$\XXX Spreadsheets\*.xls*" "\\ncxxx1\xxx_development$\Publishing\XXX\_XXX Spreadsheet Backups\

But I do not know how to add the action to create the sub-folder with the current date to the batch file.

Also, do I need to include an action in the batch file to 'End' the task?

Avatar of J0rtIT
Flag of Venezuela, Bolivarian Republic of image

I'll come up shortly to answer your question.

$SourceFolder = "\\\productiongraphics$\XXX Spreadsheets\" 
$TargetRoot = "\\ncxxx1\xxx_development$\Publishing\XXX\_XXX Spreadsheet Backups\CAP Spreadsheet Backups"

$CurrentDate = Get-Date -Format yyyy-MM-dd

#Step0: Check if the TargetRootFolder exists, if it doesn't exists create it
if(!(Test-Path $TargetRoot)){
    Write-Host -ForegroundColor Cyan "Creating new folder $TargetRoot"
    New-Item -Path $TargetRoot -ItemType directory| Out-Null #do not say anything on console that you create the folder

#Step1: GEt All the excel files on the SourceFolder
$AllFiles = Get-ChildItem -Filter *.xls* -Path $SourceFolder -Recurse

#Now For each file we will get the Current
foreach($file in $AllFiles){
    $FinalTarget ="$TargetRoot\\$CurrentDate"
    #if target folder doesn't exists create it
    if(!(Test-Path $FinalTarget)){
        Write-Host -ForegroundColor Magenta "Creating new folder $FinalTarget"
        New-Item -Path $FinalTarget  -ItemType directory| Out-Null #do not say anything on console that you create the folder
    #And copy the item with the same name on the finaltargetfodler.
    Copy-Item -LiteralPath $file.FullName -Destination "$FinalTarget\\$($file.Name)"

Open in new window

This will create the folder CAP Spreadsheet backups, (even if it doesn't exists).
Then will get all the excel files on the source path.
and then will create a folder with the today's date under the (Cap spreadsheet backups\yyyy-MM-dd\)
and finally will copy all the files from source to this latest target. if there is a need to correct something let me know since the "date" and the CAP weren't too clear for me.
Jose's Powershell should work fine but I haven't tested it. Since you said 'batch', I presume you'd like either .bat or .cmd file...

> But I do not know how to add the action to create the sub-folder with the current date to the batch file.

Make file named DateTime-YYYYMMDDHHMMSS_wmic.bat. This sets your date vars:

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _yyyy=%%L
      Set _mm=00%%J
      Set _dd=00%%G
      Set _hour=00%%H
      Set _minute=00%%I
      Set _seconds=00%%K
:: Pad digits with leading zeros
Set _mm=%_mm:~-2%
Set _dd=%_dd:~-2%
Set _hour=%_hour:~-2%
Set _minute=%_minute:~-2%
Set _seconds=%_seconds:~-2%

:: Display the date/time in ISO 8601 format:
Set _isodate=%_yyyy%-%_mm%-%_dd% %_hour%:%_minute%:%_seconds%
REM Echo %_isodate%
set DateTimeNow=%_yyyy%%_mm%%_dd%%_hour%%_minute%%_seconds%
REM echo DateTimeNow=%DateTimeNow%


Open in new window

Revise your main code accordingly. Note: This is currently in debug mode for visual reasons. When you've confirmed it looks correct, remove the ECHO prefixes.

Open a Command Window to run it.

@echo off
setlocal enabledelayedexpansion

call DateTime-YYYYMMDDHHMMSS_wmic.bat

set destdir=\\ncxxx1\xxx_development$\Publishing\XXX\_XXX Spreadsheet Backups\%_yyyy%-%_mm%-%_dd%

ECHO if not exist "%destdir%" md "%destdir%"
ECHO Copy "\\\productiongraphics$\XXX Spreadsheets\*.xls*" "%destdir%"

Open in new window

> Also, do I need to include an action in the batch file to 'End' the task?

Avatar of Andreamary


Thanks to you both for your quick responses.

Yes, you're right, NVIT, I do need a .bat file. I want to be able to run this within Windows 10 Task Scheduler at a specific time of day.

As I am not experienced in this area, I thought perhaps I could save Jose's solution as a .bat file, but received error messages so suspect it is not a .bat file...?

I had success with NVIT's solution when I ran it as outlined - thank you very much! I ran into a challenge when I tried running it in Windows 10 Task Scheduler. For the Task Scheduler, I wasn't sure what to do so I added both .bat files. When I ran the main code, the Excel files did get copied into a newly created folder, but the folder name was "--" and not named with the current date (as it was when run from the CMD line). Would you be able to guide me as to how I get these two .bat files to work together in Task Scheduler (ie., for the main .bat file to reference the DateTime-YYYYMMDDHHMMSS_wmic.bat file so the new folder is correctly named with the current date)?

Avatar of Bill Prew
Bill Prew

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
DateTime-YYYYMMDDHHMMSS_wmic.bat  must either be in the same folder as the main bat, or somewhere in the PATH. I put my bat files in a c:\utils folder
Thanks very much for your help, everyone! I was able to run Bill's solution successfully through Windows 10 Task Scheduler. :-)

Sorry, I meant to mention (for future reference to others who may view this question) that I had to make one tweak to your code, Bill - Line 11 - change the word 'datastamp' to datestamp'...


Just to confirm that I do have both .bat files in the same folder, but for some reason the folder name is showing as "--" instead of the date...

Andrea. you can safely use powershell or cmd files with task scheduler


You don't need to have both files. With a bat file is enough, and you can use any file (of the answers)... of course, you need to use the real path on the answers.

@NVIT a batch file is a synonym to say a script, on Task scheduler works any of the 3 files, regular Command (.bat, .cmd) or PowerShell (.ps1).

Fine. Still, Andrea wasn't specific, so...
NVIT - I apologize for not being more specific, which is due to my lack of knowledge/experience in this area...with the helpful answers/information you have all provided, I now have a better understanding and can (hopefully) pose my future questions more succinctly. :-)

Jose - thanks very much for sharing additional knowledge/insights.

Great forum!

All good np.
@NVIT, it was not specific so I could answer whatever I don't see the need for you to be picky about my answer.  I did answer to the author not to you or for you specifically.
Who's being picky?
Have you enabled Volume Shadow Copy on the server?  Too many people don't even know about this and while if you need long term archive copies of these sheets, Volume Shadow Copy can provide more granular and automated backups.
Thanks, Lee, for this information...I’ll look into it.

Thanks, Lee!