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
AndreamaryAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jose Gabriel Ortega CastroEE Solution Guide - CEO Faru Bonon ITCommented:
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.
0
NVITCommented:
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.
0
AndreamaryAuthor Commented:
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
0
Acronis True Image 2019 just released!

Create a reliable backup. Make sure you always have dependable copies of your data so you can restore your entire system or individual files.

Bill PrewCommented:
Give this BAT file a try.  I used YYYYMMDD as the date format, I'd recommend that easier sorting / ordering of the subfolders.

@echo off
setlocal

REM Get current date in YYYYMMDD
set DateStamp=
for /f "tokens=* skip=1" %%A in ('wmic os get LocalDateTime') do (
    if not defined DateStamp set DateStamp=%%A
)
set DateStamp=%DateStamp:~0,8%

set DestDir=\\ncxxx1\xxx_development$\Publishing\XXX\_XXX Spreadsheet Backups\%DateStamp%\

if not exist "%DestDir%" md "%DestDir%"

copy "\\ncxxx3.corp.xxxx.ca\productiongraphics$\XXX Spreadsheets\*.xls*" "%DestDir%"

Open in new window


(EDIT: Corrected typo of DataStamp to DataStamp)

»bp
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
NVITCommented:
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
0
AndreamaryAuthor Commented:
Thanks very much for your help, everyone! I was able to run Bill's solution successfully through Windows 10 Task Scheduler. :-)

Cheers,
Andrea
0
AndreamaryAuthor Commented:
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
0
AndreamaryAuthor Commented:
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
0
NVITCommented:
Lol
0
Jose Gabriel Ortega CastroEE Solution Guide - CEO Faru Bonon ITCommented:
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).
0
NVITCommented:
@Jose

Fine. Still, Andrea wasn't specific, so...
0
AndreamaryAuthor Commented:
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
0
Jose Gabriel Ortega CastroEE Solution Guide - CEO Faru Bonon ITCommented:
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.
0
NVITCommented:
Who's being picky?
0
Lee W, MVPTechnology and Business Process AdvisorCommented:
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.
0
AndreamaryAuthor Commented:
Thanks, Lee, for this information...I’ll look into it.

Cheers,
Andrea
0
Lee W, MVPTechnology and Business Process AdvisorCommented:
0
AndreamaryAuthor Commented:
Thanks, Lee!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows 10

From novice to tech pro — start learning today.