hello i got a batch file, something like this:
if %day%==monday, tuesday, wednesday, thursday, friday (
goto yes
) else (
goto no
)
Now i know the first line won't work.
What i actually want to happen:
It automatticly checks which day it is. If it is Monday to Friday, it has to go to 'yes', otherwise (saturday/sunday) to 'no'.
How to do this?
Here is an example bat file that will do this sort of thing I am sure you can think of other ways to use this sample code. For instance anytime you need an "in" list. The tricky bit is the %date:~0,3% this says expand the %date% environment variable and starting at position 0 the beginning of the string return the next 3 characters. You can learn more about this from the "set /?" command.
example: IsWeekDay.bat
#echo off
setlocal
for %%i in (Mon,Tue,Wed,Thu,Fri) do (
if "%date:~0,3%"=="%%i" goto YES
)
:NO
echo No
goto EOF
:YES
echo Yes
:EOF
endlocal
I ran across this online. Tested, and it works. Returns the day as an integer, which you can still work with.
#For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do #(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
#echo DAY = %Day%
#echo Month = %Month%
#echo Year = %Year%
As Jay has mentioned, using date /t will only work on locales where this command outputs the day of week along with the date, and won't work on other locales (e.g. Russian). If you don't mind mixing your batch files with some VBScript, here's a solution that should work on all locales.
The trick is this tiny VBScript script that outputs the day of the week as a number (1 = Sunday, 2 = Monday, ... 7 = Saturday):
WScript.Echo DatePart("w", Date)
You can run this script from your batch file, read its output and apply your logic:
for /f %%d in ('cscript dayofweek.vbs //nologo') do (
if %%d==7 goto no :: Saturday
if %%d==1 goto no :: Sunday
)
goto yes
IF %day% == monday GOTO YES
IF %day% == tuesday GOTO YES
IF %day% == wednesday GOTO YES
IF %day% == thursday GOTO YES
IF %day% == friday GOTO YES
GOTO NO
I don't have the batch fu to answer the question as asked, but, assuming this is a Windows batch file, consider executing the script using the task scheduler, which will let you set the kind of schedule you're asking for.
Here is a batch file that extracts day-of-week, day, month and year in an almost locale-neutral way.
The only locale specific thing is the spelling of the day-of-week, the rest is locale neutral.
So in English, it will return Thu for Thursday, but in Dutch that will be do (for donderdag).
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen#pluimers.com for Dutch locale
:: 20110303 - adapted by jeroen#pluimers.com for day-of-week
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: Also, in Dutch, there is a difference between %date% and date/t: the former will not include
:: the day-of-the-week, but the latter will.
:: That means the if "%date%A" LSS "A" trick does not work with %date%, we need a loop
:: to check if the day-of-the-week needs us to take tokens 2-4 in stead of 1-3:
:: if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
:: for /f "tokens=1" %%t in ('date/t') do (...)
::
:: Another difference between Dutch and English is that the Dutch date/t will prepend the day of the week in a lower case 2-letter form.
:: So the LSS "A" trick needs to be replaced with an LSS "a" trick
:: if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
:: if "%%ta" LSS "a" (set toks=1-3) else (set toks=2-4)
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
#ECHO off
set v_day_of_week=
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1" %%t in ('date/t') do (
set v_day_of_week=%%t
if "%%ta" LSS "a" (set toks=1-3) else (set toks=2-4)
)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET day_of_week=%v_day_of_week% & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
echo day of week=%day_of_week%
:EOF
Have fun with it!
--jeroen
From this answer, we have
wmic path win32_localtime get dayofweek
Expanding on this based on suggestions in this thread, we can set a dayofweek variable as follows:
#echo off
REM Unset dayofweek in case set in a previous execution of this batch file
set dayofweek=
REM Get dayofweek into a variable. Locale-specific: 0 is either Sunday or Monday.
for /F "skip=1 tokens=*" %%a in ('wmic path win32_localtime get dayofweek') do if not defined dayofweek set dayofweek=%%a
echo %dayofweek%
Note that 0 can be Sunday or Monday depending your locale.
Related
I current run the below script to get the current day minus 1 and the current month. It works great for all days and month except for the 8th of every month and August of every year. I have to change the script to setting it manually for August. Does anyone know why and is there a fix.
SET m=%date:~4,2%
SET /A m -= 1
SET m=0%m%
REM ****** SET m=08 this was used because the date was not right ******
REM SET m=08
SET currMon=%date:~4,2%/%date:~10,4%
REM ****** SET PriorMon=12/2017 this was used for Year End because the date was not right ******
REM SET PriorMon=08/2018
SET PriorMon=%m:~-2%/%date:~10,4%
This is a hybrid vb/batch script. It is a proper way to get the date -1 or whatever amount of days you want:
#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 "final=%dd%-%mm%-%yyyy%"
echo %final%
I simply echo the final result here which as far as today's date goes (for me as it is the 7th) should echo 06-09-2018
You can change the format of %final% as you please to suit your date..
Proper date calculatons in pure batch are possible but tedious.
Your approach relies on possibly unknown locale/user settings dependant date format.
From Win7 on Powershell is available as a tool:
On cmd line:
For /f "usebackq" %A in (`powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"`) Do Set Yesterday=%A
In a batch file:
For /f "usebackq" %%A in (`
powershell -Nop -C "(Get-Date).AddDays(-1).ToString('MM\/yyyy')"
`) Do Set Yesterday=%%A
Echo Yesterday=%Yesterday%
Modify the format string to your liking:
dd = day 2 places
MM = month 2 places
yyyy = year 4 places
Other characters have to be escaped with a backslash.
Hello I have batch code which zips my folder and removes the original copy. I run this as a task scheduler every month. There is one thing I been having problems with. My code is base on this on this variable on the top of my batch code call "set FILETOZIP" ... Is there a way where I can use another variable to look up the current month and year on my machine ? [ Rest of my batch code ] works find and I do not need any help with it.
Current :
set FILETOZIP=D:\Farm\201411
[Rest of code ]
Expected Code :
set FIND_YEAR_MONTH=" some date formula "
set FILETOZIP=D:\Farm\"A way to set FIND_YEAR_MONTH here "
[Rest of code ]
set FILETOZIP=D:\Farm\20%date:~10,2%%date:~4,2%
Is your basic structure - you don't tell us your date format which can be set on a user-by-user basis.
Assuming your format is Fri 11-21-14 then this picks the 10th character (start counting at character 0) for 2, then the 4th for 2. If your date-format differs, then adjust to suit.
Another way is
for /f "tokens=1-4 delims=/-. " %%a in ("%date%") do set /a filetozip=20%%d*100+1%%b-100
set "filetozip=D:\Farm\%filetozip%"
Again, the formula here depends on your date-format. Using your date elements and the delims set shown, then a date like Fri 11-21-14 would assign Fri to %%a, 11 to %%b, 21 to %%c and 14 to %%d. The mathematical gymnastics prefix the month and make it 100+the actual month number, so 100 needs to be subtracted. This is because batch treats numbers starting 0 as octal, so 08 and 09 are not valid. These become 108 and 109 - conveniently decimal.
Time settings independent:
#Echo Off
Call :GetDate.Init
Rem :GetDate.Init should be called one time in the code before call to :Getdate
Call :GetDate
set YEAR_MONTH=FINANCE%year%%month%
set file_to_zip=D:\Farm\%YEAR_MONTH%
[Rest of code ]
Goto :EOF
:GetDate.Init
Set /A "jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12"
Set /A "mon=1,tue=2,wed=3,thu=4,fri=5,sat=6,sun=7"
(
Echo .Set InfHeader=""
Echo .Set InfSectionOrder=""
Echo .Set InfFooter="%%2"
Echo .Set InfFooter1=""
Echo .Set InfFooter2=""
Echo .Set InfFooter3=""
Echo .Set InfFooter4=""
Echo .Set Cabinet="OFF"
Echo .Set Compress="OFF"
Echo .Set DoNotCopyFiles="ON"
Echo .Set RptFileName="NUL"
) >"%Temp%\~foo.ddf"
Goto :Eof
:GetDate
Set "tf=%Temp%\~%random%"
Makecab /D InfFileName="%tf%" /F "%Temp%\~foo.ddf" >NUL
For /F "usebackq tokens=1-7 delims=: " %%a In ("%tf%") Do (
Set /A "year=%%g,month=%%b,day=1%%c-100,weekday=%%a"
Set /A "hour=1%%d-100,minute=1%%e-100,second=1%%f-100")
Del "%tf%" >NUL 2>&1
Goto :Eof
A solution independent of locale settings:
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
It will give you:
20141121175755.279000+060
( YYYYMMDDhhmmss.<fraction>+/-<timedifference to UTC> )
from here, it is easy:
set datetime=%datetime:~0,6%
gives you 201411
and finally to get you pathname:
set "FILETOZIP=D:\Farm\%datetime%"
So I'm working on a final project for one of my classes, and the goal is basically to have the user input an initial investment, and the number of years the value will depreciate...it depreciates by a constant value which is determined by the investment divided by the number of years.
In the for loop, it should subtract the 'annual' from the 'bookvalue' and print out the new bookvalue for each year...the math itself works correctly (I believe?) because if I echo the values outside my for loop they are what they should be, but with the echo statement inside the for loop I don't get what I need it to output (the bookvalue doesn't change inside the loop).
Not really sure where to go with this, and Google hasn't done me very well yet. Thanks for any help that can be given!
#ECHO OFF
:HEADER
REM Program : final_q8.bat
REM Author :
REM Date :
REM Purpose : if statement integer sort
REM -----------------------------------------------
:START
CLS
SET /P INVEST="Please enter the initial investment amount: "
SET /P YEARS="Please enter the # of years the machine will be depreciated: "
SET /A ANNUAL=INVEST/YEARS
SET BOOKVALUE=%INVEST%
ECHO YEAR ANNUAL DEPRECIATION BOOK VALUE
FOR /L %%C IN (1, 1, %YEARS%) DO (
SET /A BOOKVALUE=BOOKVALUE-ANNUAL
ECHO %%C %ANNUAL% %BOOKVALUE%
)
PAUSE
:END
:: Exit and return an errorcode of 0
EXIT /B 0
Try enabling Delayed expansion:
#echo off
setlocal enabledelayedexpansion
...
Then use exclamation mark inside For loop
FOR /L %%C IN (1, 1, %YEARS%) DO (
SET /A BOOKVALUE=BOOKVALUE-ANNUAL
ECHO %%C !ANNUAL! !BOOKVALUE!
)
I am using this to get the date modified of a file:
#echo off
FOR %%? IN ("C:\some.exe") DO (
ECHO Last-Modified Date : %%~t?
)
The above returns something like: Last-Modified Date : 26/03/2013 14:43.
How can I take the date part from the above and compare it against another file which's name contains a date ie: 23-Sep-13.exe?
I need to be able to perform some code in the batch file if the file that contains the date in its name is later than the file modified version ie install the update.
#ECHO OFF
SETLOCAL
:: No doubt for international use, this could be retrieved from the registry
SET monthnames=Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
:: get last modified date of target file - your format as specified
:: (I used THIS BATCH FILE)
FOR %%i IN ("%~f0") DO SET target=%%~ti
:: parse the target date
FOR /f "tokens=1-3delims=/ " %%i IN ("%target%") DO SET targetf=%%k%%j%%i
::
:: parse name from 'other file'
SET other=23-Sep-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
:: #ECHO on
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
::
:: parse name from 'another other file'
SET other=23-Jan-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
Code takes date of (this batch) as the target (your 'C:\some.exe'- change to suit.
test then applied to two different filename-is-date+ext format filenames to test.
Can be easily adjusted if comparisons to 20th-Century date is required... :)
I currently have the following code in a batch file Backup.bat on my desktop. it is used to back up an excel spreadsheet file each day and rename it by appending the current date and time. File.xlsx is copied and pasted to a new folder as File Sun-06-24-2012 23.21.46PM.xlsx
Currently the date and time is appended as Sun-06-24-2012 23.21.46PM.xlsx but i would like to have it append as Sun-06-24-2012 11.21.46PM.xlsx using the 12 hour clock rather than 24 hour clock format.
Below is the code i am currently using in Windows XP Professional. Would anyone know how to have the time appended in 12 hour clock format rather than 24 hour clock format as it is currently in the code below.
#For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do #(
Set DayW=%%A
Set Day=%%B
Set Month=%%C
Set Year=%%D
Set All=%%A-%%B-%%C-%%D
)
#For /F "tokens=1,2,3 delims=:,. " %%A in ('echo %time%') do #(
Set Hour=%%A
Set Min=%%B
Set Sec=%%C
Set Allm=%%A.%%B.%%C
)
#For /F "tokens=3 delims=: " %%A in ('time /t ') do #(
Set AMPM=%%A
)
copy "C:\Temp\File.xlsx" "C:\Temp\DailyBackup\File %All% %Allm%%AMPM%.xlsx"
I agree with Joey's comment, I think you are better off with 24 hour format.
Also, your method for getting the date and time will break as soon as the code is transferred to another machine that uses a different date and/or time configuration.
But, here goes anyway...
You should get the entire time string from a single %TIME% expansion. Otherwise you run the risk of getting the hour:min:sec before midnight and the AMPM after midnight.
Put #ECHO OFF at the top, then you don't need to sprinkle # throughout your code.
#echo off
For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do (
Set DayW=%%A
Set Day=%%B
Set Month=%%C
Set Year=%%D
Set All=%%A-%%B-%%C-%%D
)
For /F "tokens=1,2,3 delims=:,. " %%A in ('echo %time%') do (
set /a "Hour=100%%A%%100"
set Min=%%B
set Sec=%%C
)
if %Hour% geq 12 (
set AMPM=PM
set /a "Hour-=12"
) else set "AMPM=AM"
if %Hour% equ 0 set "Hour=12"
if %Hour% lss 10 set "Hour=0%Hour%"
set "Allm=%Hour%.%Min%.%Sec%%AMPM%"
echo on
copy "C:\Temp\File.xlsx" "C:\Temp\DailyBackup\File %All% %Allm%.xlsx"
Time /t is giving you the time in 24-hour format, presumably because that's the default for your computer's locale.
As time /t doesn't appear to offer any formatting options, probably the easiest thing to do is add an extra section to your batch file to convert the 24-hour clock to 12-hour.
Somewhere under Set Hour=%%A you just need to:
Subtract 12 from the hour if it's more than 12
Change '00' into '12'
For example:
If %Hour% gtr 12 (
Set /a Hour=%Hour%-12
)
If %Hour% == 00 (
Set Hour=12
)
The /a switch on Set tells it that the value to the right of the equals sign is a numerical expression to be evaluated.
This will leave you with no leading zero on the hour if it comes out from 1 to 9. You could get around this with another if statement to add a leading zero back in, or there might be a more elegant approach!