Batch file check file get updated to today's date(System Date) - date

I want to create a batch to check if the file have been modified to today's date, what i did was to "bring in a system's date and compare it with the modified date, if they match, then trigger something. My batch file works well and displays two right dates, but the IF statement saying the date mismatch.
#ECHO OFF
for /f "tokens=1,2,3,4 delims=. " %%i in ('date /t') do set date=%%k%%j
echo %date%
pause
FOR %%a IN (D:\MyFile.txt) DO SET FileDate=%%~ta
set DATEONLY=%FileDate:~0,10%
echo %DATEONLY%
pause
if DATEONLY==date (
echo date ok
)
else (
cls
ECHO Wrong
)
PAUSE

There are the following problems:
do not use variable name date as this is a built-in variable containing the current date (type set /? for help);
the first for statement is useless, because %date% is already available;
the strings DATEONLY and date are compared literally in your if statement, you need to state %DATEONLY%==%date% instead;
the else statement must be in the same line as the closing parenthesis of the if body (type if /? for help);
So try this:
#ECHO OFF
echo %date%
pause
FOR %%a IN (D:\MyFile.txt) DO SET FileDate=%%~ta
set DATEONLY=%FileDate:~0,10%
echo %DATEONLY%
pause
if %DATEONLY%==%date% (
echo date ok
) else (
ECHO Wrong
)
PAUSE
Note: Regard that all those dates in the batch file are locale-dependent.

Here is a completely different approach:
forfiles /P . /M MyFile.txt /D +0 /C "cmd /C echo #fdate #file"
The forfiles command is capable of checking the file date. In the above command line, it:
walks through the current directory (.),
lists all files named MyFile.txt (of course there is onlyone),
but only if it has been modified +0 days after today,
and then executed the command line after the /C switch.
If MyFile.txt has been modified today (or even in future), the given command line is executed;
if it has been modified earlier than today, an error message is displayed and ERRORLEVEL is set to 1.
Notice that forfiles is not a built-in command and might not be available on your operating system.

Related

Using %date% in batch script

I want to have some code like this:
if %date% equ "Mon" echo do this do that
but the cmd window closes after encountering this code, even if I put
pause
after it.
How do I fix this?
Here's a complete cmd file that will give you what you need. The important bit is all in the getDow function and, hopefully, it's commented well enough to understand. First, the test harness:
#echo off
rem Test harness bit - just get current date and compare with getDow.
date /t
call :getDow num long short
echo Day of week is %num%, %long%, %short%
goto :eof
The function itself is:
rem Usage: call :getDow <num> <long> <short>
rem <num> will receive the numeric form (0-6).
rem <long> will receive the long form (e.g., Monday).
rem <short> will receive the short form (e.g., Mon).
:getDow
rem Create local scope to prevent information leakage.
setlocal enableextensions enabledelayedexpansion
rem Create array for translation.
set idx=0
for %%a in (Sunday Monday Tuesday Wednesday Thursday Friday Saturday) do (
set dow[!idx!]=%%a
set /a "idx += 1"
)
rem Get the numeric day of week, mmi command will
rem output 'DayOfWeek=N' and we just extract N.
for /f "tokens=2 delims==" %%a in ('WMIC Path Win32_LocalTime Get DayOfWeek /value ^| findstr "DayOfWeek="') do (
set localNum=%%a
)
set localStr=!dow[%localNum%]!
rem Properly end scope but let selected information leak.
endlocal&&set %1=%localNum%&&set %2=%localStr%&&set %3=%localStr:~0,3%
goto :eof
A sample run of that script gives:
Tue Jun 05
Day of week is 2, Tuesday, Tue
You probably want to use:
IF /I "%DATE:~,3%"=="Mon" (Echo Do this
Echo Do that)
Or possibly:
IF NOT "%DATE:Mon=%"=="%DATE%" (Echo Do this
Echo Do that)
However neither of those are safe or robust methods in anything other than your specific current user environment.
This is how I'd get the day of the week into a variable using a batch file with WMIC:
For /F %%A In ('WMIC Path Win32_LocalTime Get DayOfWeek') Do For %%B In (
Monday.1 Tuesday.2 Wednesday.3 Thursday.4 Friday.5 Saturday.6 Sunday.0
) Do If "%%~xB"==".%%A" Set "WDName=%%~nB"
Line 2 can be optionally adjusted to start with Sunday.0 Monday.1 etc. if necessary or Lunes.1 Martes.2 etc. depending upon your language.
You could then use:
If "%WDName%"=="Monday" (Echo Do this
Echo Do that)
Although (Get-Date).DayOfWeek in PowerShell seems so much simpler.

BATCH script: Cannot get modified date for file in nested loop

I am having trouble getting the date modified for my file from within a nested loop.
I am running this batch script:
#ECHO OFF
SETLOCAL EnableDelayedExpansion
net use S: \\devfs\edcsrc\epoletto\campusanyware
SET CLIENTS= DEMO
FOR %%a in (%CLIENTS%) DO (
S:
CD AD
FOR %%B in (*.cbl) DO (
set file=%%B
echo !file!
for %%c in (!file!) do (echo %%~ta))
)
pause
net use S: /delete /Y
ECHO.
Here is my output:
The command completed successfully.
ad1.cbl
ECHO is off.
ad2.cbl
ECHO is off.
ad3.cbl
ECHO is off.
Press any key to continue . . .
All of my file names are correct, but when the script goes into the the third FOR loop (for %%c in (!file!) do (echo %%~ta))), I cannot get the date/time modified for my file.
As a proof of concept, I tried this same logic from the command line from within the directory:
for %B in (*.cbl) DO (for %a in (%B) do echo %~ta)
And my output from that command was (including initial command):
V:\>for %B in (*.cbl) DO (for %a in (%B) do echo %~ta)
V:\>(for %a in (ad1.cbl) do echo %~ta )
V:\>echo 05/02/2017 11:32 AM
05/02/2017 11:32 AM
V:\>(for %a in (ad2.cbl) do echo %~ta )
V:\>echo 04/18/2017 02:04 PM
04/18/2017 02:04 PM
V:\>(for %a in (ad3.cbl) do echo %~ta )
V:\>echo 04/27/2017 11:46 AM
04/27/2017 11:46 AM
I'm confused as to why I can't get these dates from within my script. My ultimate goal is to check the date for each file and then execute another command dependent on that date. Right now I'm just trying to verify I can get the date using echo. Any suggestions are appreciated!
Thank you!
Instead of
for %%c in (!file!) do (echo %%~ta))
use
for %%c in (!file!) do (echo %%~tc))
because you want the modified time of %%c, not of %%a.
:)

Use Variable insted of Get-Date in powershell

I am using PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')" in batch script.
I want to use a variable instead of Get-Date function. Is it possible?
ADate is the variable name!
Edited:
As suggested, my script is:
For /F UseBackQ %%A In (
`PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "Freq=%%A"
Adate is simple string which comes from the file name, and has a value like 16112016.
You need to use a for loop to get the output of an external command in a batch variable:
#echo off
for /f "usebackq tokens=*" %%d in (`powershell "..."`) do set "adate=%%d"
echo %adate%
The usebackq and backticks are just so you don't need to escape the nested single quotes in your command string.
Ok. I got my crystal ball and asked it: "What is the solution here?", and it replied: "Change
PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"
by
PowerShell "(Get-Date -Date '!Adate:~4!-!Adate:~2,2!-!Adate:~0,2!').AddDays(-7).ToString('ddMMyyyy')"
", but I have no idea what it is talking about! ;)
You can store the output of the powerShell command into a file and then read that file after that delete that temporary file.
PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')" >temp.txt
set /p myVarDate= < date_Shell.txt
echo Date from Shell %myVarDate%
del temp.txt
The following takes the last modified time from a known file's properties and creates a variable with a date seven days earlier, (obviously changing C:\Test\TestFile.ext as necessary):
For /F UseBackQ %%A In (
`PowerShell "((gi 'C:\Test\TestFile.ext').LastWriteTime).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "ADate=%%A"
Edit
The following example takes a date string with a known format, (in this case provided in two variables). It then converts that string to a date object, subtracts seven days and sets it back to a string in the new %ADate% variable:
#Echo Off
Set "DateStr=16112016"
Set "DFormat=ddMMyyyy"
For /F UseBackQ %%A In (`Powershell^
"([datetime]::ParseExact('%DateStr%','%DFormat%', [System.Globalization.CultureInfo]::CurrentCulture)).AddDays(-7).ToString('%DFormat%')"
`) Do Set "ADate=%%A"
Echo(%ADate%
Timeout -1

Re-naming a file name to include yesterday's date using command prompt

I am trying to rename some log files to yesterday's date when the batch file creates a new file of same name every night.
We can rename the file to today's date using the below cmd
ren SampleDTE.TXT SampleDTE-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.TXT
This results in file renamed to // SampleDTE-YYYYDDMM_hhmm.TXT
SampleDTE-20132712_1243.TXT
I wanted to know how to re-name the file to yesterday's date. Something like
SampleDTE-20132612_1243.TXT
Thanks in advance
The easy way - assuming that you run this regularly, once per day
FOR /f %%a IN (sampledteyesterday.txt) DO ECHO ren SampleDTE.TXT SampleDTE-%%a_%time:~0,2%%time:~3,2%.txt
> sampledteyesterday.txt ECHO %date:~10,4%%day%%date:~4,2%
Note - ren command simply ECHOed. when verified, remove the ECHO keyword before the REN to activate.
You'll need to set up your sampledteyesterday.txt file containing a single line YYYYDDMM for yesterday to initialise.
Suggestion: use YYYYMMDD which sorts easier or more logically...
You will have to use a variable and do the math:
set /a day=%date:~7,2% - 1
ren SampleDTE.TXT SampleDTE-%date:~10,4%%day%%date:~4,2%_%time:~0,2%%time:~3,2%.TXT
To avoid date arithmetics, you can store yesterday date in, eg, file.
yesterday.txt (contains today and yesterday):
20131227 20131226
Batch file:
REM Get today (to check if yesterday.txt is valid):
SET today=%DATE:~10,4%%DATE:~7,2%%DATE:~4,2%
REM Read file:
FOR /F "TOKENS=1,2" %%d IN (yesterday.txt) DO (
SET stored_today=%%d
SET yesterday=%%e
)
REM If stored_today not equal to today, assume yesterday is stored_today and update file:
IF NOT "%stored_today%" == "%today%" (
SET yesterday=%stored_today%
>yesterday.txt ECHO %stored_today% %today%
)
REM Test if yesterday is set, exit otherwise.
IF "%yesterday%"=="" ECHO Yesterday unknown! Try again tomorrow.&GOTO:EOF
To make it work correctly first time, yesterday.txt must be manually filled.
This will get yesterdays date, using VBS in a batch file.
It's reliable in all locales, whereas the %date% variable can be different on different computers, and different users.
#echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "date-yesterday=%yyyy%-%mm%-%dd%"
echo Yesterday was "%date-yesterday%"
pause

Comparing a modified file date with the current date in a batch file

I'm required to write a batch file to do a few things
Initially I thought my problem was very simple - capture the modified date of a txt file located in a specified directory, compare that date to the current date and if they are the same do something. If they are not then do something else.
The line I use to capture the current date is:
%date%
The lines I use to capture the modified date of my specified file is:
SET filename="C:\New Folder\New.txt"
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
ECHO %filedatetime:~0,-6% >> %destination%
In the above case I'm simply using echo to see what is returned and it seems as if the date is returned but I get extra information:
2012/02/19 02
I would like to know how to get the above values where they are comparable as well as how to compare them properly.
Working with dates is much harder in batch then it ought to be.
There is one command that can make your job easy in this case. FORFILES has the ability to process files that have been modified since a particular date. Use FORFILES /? from the command line to get documentation on its use.
This simple command will list all files that have been modified today:
forfiles /m * /d 0
If at least one file is found, then ERRORLEVEL is set to 0, else ERRORLEVEL is set to 1.
You have a specific file, so you can use
forfiles /m %filename% /d 0
if %errorlevel% == 0 (
echo The file was modified today
REM do whatever else you need to do
) else (
echo The file has not been modified today
REM do whatever else you need to do
)
There is a more concise way to do the above. The && operator is used to conditionally execute commands if the prior command was successful, || is used to conditionally execute commands if the prior command failed. However, be careful, the || commands will also execute if the && command(s) failed.
forfiles /m %filename% /d 0 && (
echo The file was modified today
REM do whatever else you need to do
) || (
echo The file has not been modified today
REM do whatever else you need to do
)
I like dbenham's way, but if you want to make your code work you can do like this:
set currentDate=%date%
SET filename="C:\MyFile.txt"
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
IF %filedatetime:~0, 10% == %currentDate% goto same
goto notsame
:same
echo Dates the same, do some code here
goto next
:notsame
echo Dates NOT the same, do some code here
goto end
:next
Thought it would be worth knowing how to make yours work just in case you need it again.
Apart from the issues raised in the comments appended to the TechNet article that documents ForFiles ForFiles Documentation on Microsoft TechNet, there is another issue that is mentioned, but only if you read between the lines regarding time zone being ignored. Since ForFiles evaluates the Modified date reported in Local time, it will treat a file modified at 02:01 EST as older than a file modified at 02:59 EDT.
dbenham way worked but I noticed forfiles errorlevel is supposed to be 1 for errors so revised to be this:
forfiles /p C:\Users\[path] /m "special_file.txt" /d 0
IF ERRORLEVEL 1 (echo boo unsucessful and old file) else (echo yay sucessful and updated today)
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/forfiles
https://ss64.com/nt/errorlevel.html