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