::================================================
:: YESTERDAY.BAT
::
:: Function to return yesterday's date
::================================================
@echo off
set /a d=%date:~0,2%
set /a m=%date:~3,2%
set /a y=%date:~6,4%
:loop
set /a d-=1
if %d% lss 1 (
set d=31
set /a m-=1
if %m% lss 1 (
set m=12
set /a y-=1
)
)
xcopy /d:%m%-%d%-%y% /l . .. >nul 2>&1 || goto loop
echo %d%/%m%/%y%
set /a d=%date:~0,2%
set /a m=%date:~3,2%
set /a y=%date:~6,4%
If your system's date format differs from DD/MM/YYYY then you will need to edit these three lines or provide some other method of delivering the date to the batch file in order for the rest of the code to work correctly.
:loop
set /a d-=1
if %d% lss 1 (
set d=31
set /a m-=1
if %m% lss 1 (
set m=12
set /a y-=1
)
)
xcopy /d:%m%-%d%-%y% /l . .. >nul 2>&1 || goto loop
In all cases, if 'd' is decremented past '1' it is reset to '31' and 'm' (month) is decremented. Likewise, if 'm' is decremented past '1' it is reset to '12' and 'y' (year) is dcremented.
echo %d%/%m%/%y%
Notice the order in which D, M and Y are re-assembled - they are consistent with the input.
set d= %d%
set m=0%m%
echo %d:~-2%/%m~-2%/%y%
And that's about all you need to know.
for /f %%a in ('yesterday') do set yesterday=%%a
As a function added to your own code, you might call it like this:
for /f %%a in ('call :yesterday') do set yesterday=%%a
'%%a' is set to the date given by the function YESTERDAY.BAT, this is then assigned to the variable 'yesterday'.
call yesterday >file
call yesterday|find . . .
You can take input from the command line rather than DATE itself by replacing the three SET statements in the input section with something like this:
for /f "tokens=1-3 usebackq delims=/" %%a in ('%1') do (
set d=%%a
set m=%%b
set y=%%c
)
Note: That would make the function return "The Day Before x" rather than yesterday.
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (2)
Commented:
Thanks for this great article.
When I run "Batch File as Administrator" it is working properly, however, when I normally run it by double clicking .bat file it doesn't come out of loop.
Could you please suggest ?
Looking for your further support.
Best Regards
Bhavik
Error-Cmd.JPG
Correct.JPG
Author
Commented:Have you edited the batch file code?
If you intend to run this batch file by double-clicking on it then I would suggest adding a PAUSE command at the end of the batch file like this:
Open in new window
This will pause output to your display and should work with, or without, administrative privileges.Hope that helps.