-1
@echo off
d:
cd mljewel.12
rar a -r mlyedek.rar
cd\
f
cd yedek
md %1
z:
cd yedek
md %1
copy D:\MLJEWEL.12\mlyedek.rar f:\yedek\%1
copy D:\MLJEWEL.12\mlyedek.rar z:\yedek\%1 
del D:\MLJEWEL.12\mlyedek.rar
pause

hello i have bat file saved as backup.bat and i have to run this file every day with date tagged with it. So what i do is I press win+R and write "backup 06062022" date goes to %1 in the code and a folder named 06062022 gets created. basicly what i need is to backup a certain folder everyday on startup with any indication that contains the date

Mofi
  • 46,139
  • 17
  • 80
  • 143
WaLeK
  • 1
  • Your could run the script with ScheduledExecutorService, you could look at this: https://stackoverflow.com/questions/20387881/how-to-run-certain-task-every-day-at-a-particular-time-using-scheduledexecutorse – y434y Jun 06 '22 at 14:17
  • use a scheduled task for "run each day at startup" and [get the date from the system](https://stackoverflow.com/questions/7727114/batch-command-date-and-time-in-file-name/18024049#18024049). Tip: use ISO format `YYYYMMDD` so your backup folders are properly sorted. – Stephan Jun 12 '22 at 10:00

1 Answers1

0
@echo off
setlocal
set "Datestamp="
set /a Datestamp=%1 2>nul
if not defined Datestamp (
 for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
 set /a DateStamp=Year*10000+Month*100+Day
)

then

d:

etc., etc. from your code, but replace %1 with %Datestamp%

How it works:

The setlocal ensures that changes made to the environment are discarded when the batch ends.

The first set of datestamp "sets" the value to nothing, which causes datestamp to be undefined.

If you supply a parameter, this will be used for your datestamp. If you don't, an error message will be produced which will be suppressed by the 2>nul and datestamp will remain undefined.

If datestamp is undefined, the for instruction runs wmic and picks those lines that contain = using find (the ^ "escapes" the pipe | and tells cmd that | is part of the parenthesised instruction, not of the for)

This will produce something like

Day=12
DayOfWeek=0
Hour=18
Milliseconds=
Minute=1
Month=6
Quarter=2
Second=47
WeekInMonth=3
Year=2022

and these variables will be set by the set instruction that the for executes.

Then calculate the datestamp as YYYYMMDD (20220612)

It's to your advantage that the date is expressed in this manner as the directories then produced will be listed by dir sorted in order. using the format you suggest will not do this and is confusing. Is 06062022 in MMDDYYYY order, or DDMMYYYY order, for instance?

So - these revisions will allow the batch to be run as it always has run, but omitting the parameter will cause it to calculate the current date and use that.

Then you can use task scheduker to eun the batch with no parameter and it all proceeds automagically.

Stephan
  • 53,940
  • 10
  • 58
  • 91
Magoo
  • 77,302
  • 8
  • 62
  • 84