batch file with two variable dates - batch-file

I'm looking to include a script in my batch file that copies file "X" from a directory, say, "[...]\2017\08 August\08.28" (previous weekday-1) to a directory: "2017\08 August\08.29" (previous weekday).
I currently do have two batch files which perform number of things for yesterday or 3 days ago (executing on Mondays), but I'd like to include that one line as well and preferably merge that into one file that automatically detects if the previous day is weekday, or not. What I do have now, simplified, is:
#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%"
if %MM%==08 (
set "mon=August"
)
copy "\2017\08 August\08.28\X" "\%YYYY%\%MM% %mon%\%MM%.%DD%"
How could I make that automatically adjustable?

The question wanders around a bit. The key seems to be that you want to know if yesterday was a weekday. This should help:
#echo off
set IYW_CURDAT=%DATE%
set IYW_CURDOW=%IYW_CURDAT:~0,3%
set IYW_YESWDY=TRUE
if /I "%IYW_CURDOW%" EQU "Sun" set IYW_YESWDY=FALSE
if /I "%IYW_CURDOW%" EQU "Mon" set IYW_YESWDY=FALSE
if [%IYW_YESWDY%] == [TRUE] echo Yesterday was a weekday
if [%IYW_YESWDY%] == [FALSE] echo Yesterday was NOT a weekday
set IYW_CURDAT=
set IYW_CURDOW=
set IYW_YESWDY=

Related

Batch to check file size before proceed to printing

This batch currently im using to print our daily report from a website then saved it as pdf (as a backup) and print one hard copy.
During saving the pdf, there will be 2 different size of pdf files generated daily(1 day 1 pdf only). Size of some pdf will be more than 20kb which contain our daily report and some will be around 9kb (8485bytes) (empty report because that day no sales).
My target now to save paper by preventing those empty report will not be print on that day. So how to add some code into my current code so that before printing, batch will check for file size before go to printing job. If possible, I want to create a msgbox too so that user will be prompt when no pdf will be print because of report empty.
Refer to code below:
Setting date parameter
Creating folder and subfolders
Using wkhtmltopdf to webpage to PDF
Check file size before printing
This is what I want to add. If generated pdf size more that 9kb, proceed to No 5 and No 6 automatically. Else, prompt user using msgbox "No report for today, Press OK to shutdown computer"
Printing
Shutting down computer
#echo off
title Daily Report to PDF
REM ---------------------------------------------------------------------------
REM 1. Setting date parameter
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set date=%%a
set month=%date:~4,2%
if %month%==01 set monthname=January
if %month%==02 set monthname=Febuary
if %month%==03 set monthname=March
if %month%==04 set monthname=April
if %month%==05 set monthname=May
if %month%==06 set monthname=June
if %month%==07 set monthname=July
if %month%==08 set monthname=August
if %month%==09 set monthname=September
if %month%==10 set monthname=October
if %month%==11 set monthname=November
if %month%==12 set monthname=December
for /f %%i in ('wmic path win32_localtime get dayofweek ^| findstr [0-9]') do set dayofweek=%%i
if %dayofweek%==1 set dow=(Mon)
if %dayofweek%==2 set dow=(Tue)
if %dayofweek%==3 set dow=(Wed)
if %dayofweek%==4 set dow=(Thu)
if %dayofweek%==5 set dow=(Fri)
if %dayofweek%==6 set dow=(Sat)
if %dayofweek%==7 set dow=(Sun)
REM ---------------------------------------------------------------------------
REM 2. Creating folder and subfolders
set dir1="%USERPROFILE%\Desktop\TEST"
set day=%date:~6,2%
set months=%monthname:~0,3%
set year=%date:~0,4%
set fulldate=%day%%months%%year%%dow%
md %dir1%\"YEAR %year%"\%monthname% 2>NUL
cd %dir1%\"YEAR %year%"\%monthname%\
md a b c 2>NUL
REM ---------------------------------------------------------------------------
REM 3. Using wkhtmltopdf to webpage to PDF
set dir2="%USERPROFILE%\Desktop\TEST\YEAR %year%\%monthname%"
echo.
echo Saving report as %fulldate%.pdf
wkhtmltopdf -q -g https://www.google.com %dir2%\c\%fulldate%.pdf
echo.
REM ---------------------------------------------------------------------------
REM 4. Check file size before printing
REM ---------------------------------------------------------------------------
REM 5. Printing
echo Printing %fulldate%.pdf
echo.
echo "C:\\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe" /t %dir2%\c\%fulldate%.pdf
REM ---------------------------------------------------------------------------
REM 6. Shutting down computer
shutdown -s -t 60 -c
PAUSE
::EXIT
Here's an example batch-file which tries to mimic your posted example and which includes some changes, predominantly the Setting of date variables.
#Echo Off
Title Daily Report to PDF
Rem ------------------------------------------------------------------------
Rem 1. Setting date variables
Set "_WeekDays=Sunday Monday Tuesday Wednesday Thursday Friday Saturday"
For /F %%A In ('WMIC Path Win32_LocalTime Get /Value^
^|FindStr "[0-9]$"')Do Set "_%%A"
For /F "Tokens=1%_DayOfWeek%" %%A In (". . . . . . . . . %_WeekDays%"
)Do Set "_DayFullName=%%A"
Set "_DayShortName=%_DayFullName:~,3%"
For %%A In (Day Hour Minute Month Second
)Do Call Set "_%%A=0%%_%%A%%" & Call Set "_%%A=%%_%%A:~-2%%"
For %%A In (January.01 February.02 March.03 April.04 May.05 June.06
July.07 August.08 September.09 October.10 November.11 December.12
)Do If ".%_Month%"=="%%~xA" Set "_MonthFullName=%%~nA"
Set "_MonthShortName=%_MonthFullName:~,3%"
Set "_FullDateString=%_Day%%_MonthShortName%%_Year%%_DayShortName%"
Rem ------------------------------------------------------------------------
Rem 2. Creating folder and subfolders
Set "_Dir1=%UserProfile%\Desktop\TEST\YEAR %_Year%\%_MonthFullName%"
For %%A In (a b c)Do MD "%_Dir1%\%%A" 2>NUL
Rem ------------------------------------------------------------------------
Rem 3. Using wkhtmltopdf to convert webpage to PDF
Echo=
Echo Saving report as %_FullDateString%.pdf
wkhtmltopdf -q -g https://www.google.com "%_Dir1%\c\%_FullDateString%.pdf"
Echo=
Rem ------------------------------------------------------------------------
Rem 4. Printing files with sizes over 8485 bytes
Set "_Exe1=%ProgramFiles(x86)%\Foxit Software\Foxit Reader\Foxit Reader.exe"
For %%A In ("%_Dir1%\c\%_FullDateString%.pdf")Do If %%~zA GTR 8485 (
Echo Printing %%A&Echo=&"%_Exe1%" /t "%_Dir1%\c\%_FullDateString%.pdf")
Rem ------------------------------------------------------------------------
Rem 5. Shutting down computer
ShutDown /S /T 60
Note: This script assumes that the executable wkhtmltopdf is able to run from the current directory at the time the batch script is run.

Date Output error in Batch Script only on the 8th

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.

I want to retrieve data of particular date If user provide? Otherwise, it retrieves T-1 date which is currently fetching. Through Batch file

I have created a batch file which retrieves T-1 data from the database. But I want to retrieve data of backdated data of date which user enter through cmd.
Can you please help me on this?
I want to retrieve data of particular date If user provide? Otherwise, it retrieves T-1 date which is currently fetching:
set qty=-1
:loop4weekends
set "separator1=-"
set "separator2=_"
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%qty%,now)
echo>>"%temp%\%~n0.vbs" d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^&_
echo>>"%temp%\%~n0.vbs" right(100+month(s),2)^&_
echo>>"%temp%\%~n0.vbs" right(100+day(s),2)^&_
echo>>"%temp%\%~n0.vbs" d
for /f %%a in ('cscript //nologo "%temp%\%~n0.vbs"') do set result=%%a
del "%temp%\%~n0.vbs"
endlocal& set "YY=%result:~0,4%" & set "MM=%result:~4,2%" & set "DD=%result:~6,2%" & set "daynum=%result:~-1%"
:: if the daynum is a weekend then loop to get the friday
set "weekend="
if %daynum% EQU 1 set weekend=1&set "qty=-3"
if %daynum% EQU 7 set weekend=1&set "qty=-2"
if defined weekend goto :loop4weekends
set "day=%YY%%separator1%%MM%%separator1%%DD%"
set "day1=%YY%%separator2%%MM%%separator2%%DD%"
sqlcmd -U %SQLServerUserName% -P %SQLServerPassword% -S %MachineIP% -Q "exec P_SP #companyFundIDs=N'',#inputDate=N''" -d %ClientDB% -o "Fil_Trade_%day1%.csv" -s"," -W
ECHO CSV file has been generated successfully
pause
You want an default value, unless the user enters something different. That's quite easy, because set /p leaves the variable unchanged, when user just presses ENTER. So just define a default value before asking the user:
set "result=defaultValue"
set /p "result=Enter date ([ENTER] for default "%result%"): "
echo %result%
You should add a bit of code to verify, if the string the user entered is a valid date. Here is an example.

Batch file to delete files older than N hours or minutes

I see this - Batch file to delete files older than N days
But how can I delete files older than N hours or minutes?
Thanks.
Neither of the solutions here worked for me. They are very innovative solutions, and the first one (.net/FileTimeFilerJS.bat [sic]) actually worked once for me. When I tried to call it on another folder, however, it simply crashed. I tried the second one (jscript/FileTimeFilterJs.bat), but it did not successfully delete all files older than one hour.
My solution requires an executable, but I found it was the best solution for me.
I downloaded FindUtils from GnuWin32, and extracted 3 files (you have to download the two zips below): libintl3.dll, libiconv2.dll, and find.exe (combined they are about 1MB in size). I rename find.exe to gnu_find.exe just to avoid the Windows FIND command.
Then, you can run the beautiful GNU command (below command is for all zip files older than 120 minutes in folder specified by environment variable %fldr%):
gnu_find %fldr% -name *[.:]zip -type f -mmin +120 -delete
Instead of *.zip, I use *[.:]zip, because Windows 7+ will expand the *.zip before find can use it.
Find Utils bin
Find Utils deps
Its challenging to do this (independent of time date settings) even with WSH\Jscript\VBscript as WSH does not return date object when you request the date/time properties of a file ,but a string that depends on time settings (wmi could be used but this will hit the performance).
I suppose you have installed .net framework which make the task far more easier.
Here's a hybrid tool that should work in your case. You can save it with whatever name you want. Here's how to use it (its called FileDateFilterJS.bat in this example):
#echo off
for /f "tokens=* delims=" %%# in ('FileDateFilterJS.bat "." -hh -5') do (
echo deleting "%%~f#"
echo del /q /f "%%~f#"
)
pause
Where the hours are 5 - -hh -5 and directory is current - "." .You can remove the echo before del command.
This script took me far more time than I've expected (despite I've researched the topic and has some parts ready) and is no so heavy tested so probably is still not buggy-free.And I suppose the help message and options could be improved.
#echo off
cd /d "your file path"
:: delete files 3 hours ago. If you want other condition, refer https://www.w3schools.com/asp/func_dateadd.asp
echo wscript.echo dateadd("h",-3,now())>GetOldDate.vbs
for /f "tokens=1,2 delims= " %%i in ('cscript /nologo GetOldDate.vbs') do (
set d=%%i
set t=%%j
)
echo "%d%"
echo "%t%"
for /f "tokens=1,2,3 delims=/" %%a in ("%d%") do (
set y=%%a
set m=%%b
set d=%%c
)
for /f "tokens=1,2,3 delims=:" %%a in ("%t%") do (
set h=%%a
set mm=%%b
set s=%%c
)
if %m% LSS 10 set m=0%m%
if %d% LSS 10 set d=0%d%
if %h% LSS 10 set h=0%h%
if %mm% LSS 10 set mm=0%mm%
set OldDate=%y%/%m%/%d% %h%:%mm%
echo "%OldDate%"
del GetOldDate.vbs
for %%a in (*) do (
if "%%~ta" lss "%OldDate%" (
echo %%a
echo "%%~ta"
del %%a
)
)
Deleting files:
#echo off
echo >%temp%\temp.vbs for each File In CreateObject("Scripting.FileSystemObject").GetFolder("[path_file]").Files
echo >>%temp%\temp.vbs If DateDiff("n",File.DateCreated,Now) ^> 30 Then File.Deletee
echo >>%temp%\temp.vbs next
cscript /nologo %temp%\temp.vbs
Exit /b
Deleting folders:
#echo off
echo >%temp%\temp.vbs for each Folder In CreateObject("Scripting.FileSystemObject").GetFolder("[Path_folder]").subFolders
echo >>%temp%\temp.vbs If DateDiff("n",Folder.DateCreated,Now) ^> 30 Then Folder.Delete
echo >>%temp%\temp.vbs next
cscript /nologo %temp%\temp.vbs
Exit /b
To vary the time difference, we need to substitute in DateDiff("n",[Folder or File].DateCreated,Now) ^> 30, the condition (in this case 30 minutes).
.DateCreated can be changed by: .DateLastAccessed or .DateLastModified.
Time difference: "yyyy" Year, "m" Month, "d" Day, "h" Hour, "n" Minute, "s" Seconds.
["Path_file o Path_folder"] has to be sustituded for the target file or folder.
Here's another script that relies only on WSH/JSCRIPT and almost the same interface (and does not require .net installed).To show files older than 5 hours use:
FileTimeFilterJS.bat "." -hh -5 -filetime modified

Batch File Comparing Database backup with condition

I would like to ask about this matter i want to backup the database table every 10mins and compare with the existing database table.
here
#echo off
set tbluser=user_tbl
set tblticket=ticket_tbl
::REM set Date
set datetoday=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
for /F "tokens=5-8 delims=:. " %%i in ('echo.^| time ^| find "current" ') do (
set hh=%%i
set mm=%%j
)
set datentime = %datetoday%%hh%%mm%
::set path
set dBackup="D:\dbBackup\dailybackup"
set wBackup="D:\dbBackup\weeklybackup"
set zip="C:\Program Files\7-Zip\7z.exe"
FC /B %wBackup%\%tblticket%.sql %dBackup%\%tblticket%_%datentime%.sql
IF %wBackup%\%tblticket%.sql EQU %dBackup%\%tblticket%_%datentime%.sql (DEL %dBackup%\%tblticket%.sql) ELSE (%zip% a -tgzip %dBackup%\%tblticket%_%datentime%.sql.gz %dBackup%\%tblticket%_%datentime%.sql
del %dBackup%\%tblticket%_%datentime%.sql)
#pause
1 - I don't know how to backup your database. No info included.
2 - You get the current date from %date% environment variable. Do the same for time with %time% variable
3 - To test for equality of the two files, after using FC to compare, check errorlevel to know if command failed or not
FC /b file1 file2 > nul
if errorlevel 1 (
rem files are different
) else (
rem files are identical
)

Resources