Avatar of Andreamary
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 "\\ncxxx3.corp.xxxx.ca\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?

Thanks,
Andrea
Windows 10Windows BatchWindows OS

Avatar of undefined
Last Comment
Andreamary

8/22/2022 - Mon
Jose Gabriel Ortega Castro

I'll come up shortly to answer your question.

$SourceFolder = "\\ncxxx3.corp.xxxx.ca\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.
NVIT

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
)
:s_done
:: 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%

GOTO:EOF

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 "\\ncxxx3.corp.xxxx.ca\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?

No.
Andreamary

ASKER
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)?

Thanks!
Andrea
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER CERTIFIED SOLUTION
Bill Prew

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
NVIT

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
Andreamary

ASKER
Thanks very much for your help, everyone! I was able to run Bill's solution successfully through Windows 10 Task Scheduler. :-)

Cheers,
Andrea
Andreamary

ASKER
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'...

Cheers,
Andrea
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Andreamary

ASKER
Hi NVIT,

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
NVIT

Lol
Jose Gabriel Ortega Castro

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

https://social.technet.microsoft.com/wiki/contents/articles/38580.configure-to-run-a-powershell-script-into-task-scheduler.aspx

So....


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).
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
NVIT

@Jose

Fine. Still, Andrea wasn't specific, so...
Andreamary

ASKER
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!

Andrea
Jose Gabriel Ortega Castro

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.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
NVIT

Who's being picky?
Lee W, MVP

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.
Andreamary

ASKER
Thanks, Lee, for this information...I’ll look into it.

Cheers,
Andrea
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Lee W, MVP

Andreamary

ASKER
Thanks, Lee!