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.
Related
How do I add the time to this batch file when I rename the file?
The results look like this but need time also: Daily Report_Wed 08222018.pdf
#echo off
Pushd c:\Temp
pdftk *.pdf cat output %fn%.pdf
ren %fn%.pdf %fn%.xxx
del *.pdf
ren %fn%.xxx "Daily Report".pdf
for /f "tokens=1-3 delims=/" %%a in ('echo %date%') do set today=%%a%%b%%c
for %%f in (*.pdf) do ren "%%f" "%%~nf_%today%%%~xf"
mkdir "Daily Reports for Review"
move *.pdf "Daily Reports for Review"
Here's something that could get you close to what you want (I modified your 1st for loop):
e:\Work\Dev\StackOverflow>echo Date: [%date%], Time: [%time%]
Date: [2018-08-22], Time: [22:51:36.23]
e:\Work\Dev\StackOverflow>for /f "tokens=1-6 delims=/-:., " %a in ('echo %date: =0%-%time: =0%') do (echo set now=%a%b%c%d%e%f)
e:\Work\Dev\StackOverflow>(echo set now=20180822225136 )
set now=20180822225136
Notes:
Since I am directly in cmd window, and you're in a batch file you have to double the percent sign (%) for parameters (%a -> %%a, %b -> %%b, ... like you already have in your snippet). For more details, check [SS64]: Double %% symbols why are they needed in a batch file?
As you probably noticed (most likely due to "Regional settings"), my date format differs than yours (that's why I added the hyphen (-) in the delims list; also the items ordering is reversed), so you might get slightly different behaviors on different computers (things will get even worse on non English locales, as #Stephan noticed), so it's not a reliable solution (I guess this is batch processing generic)
Here's an untested example for you which uses WMIC to retrieve non locale dependent date and time values:
#Echo Off
If Exist "C:\Temp\*.pdf" (CD /D "C:\Temp") Else Exit /B
Rem The values below can be modified according to your language or preferred day names
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 "DayName=%%A"
For %%A In (Day Hour Minute Month Second) Do Call Set "%%A=0%%%%A%%" & Call Set "%%A=%%%%A:~-2%%"
Rem Choose the output %FileName% you want from the following variables:
Rem %Year% e.g. 2018
Rem %Quarter% e.g. 3
Rem %Month% e.g. 08
Rem %WeekInMonth% e.g. 4
Rem %Day% e.g. 22
Rem %DayOfWeek% as an integer where Monday from %WeekDays% is 1 e.g. 3
Rem %DayName% as a string taken from %WeekDays% e.g. Wednesday
Rem %Hour% in 24 hr format e.g. 21
Rem %Minute% e.g. 57
Rem %Second% e.g. 53
Set "FileName=%DayName% %Month%%Day%%Year%%Hour%%Minute%%Second%"
Rem Choose the full or relative output directory name
Set "DirName=Daily Reports for Review"
If Not Exist "%DirName%\" MD "%DirName%"
PDFTK *.pdf cat output "%DirName%\%FileName%.pdf" && Del /Q *.pdf
You will need to include the full or relative path to PDFTK on the last line if it is not located in the current working directory, (C:\Temp), or in %PATH%. Other than that, you should only make modifications to values on lines beginning with Set.
Empty lines and those Remarked can be optionally removed once you've made your modifications.
I am trying to set a housekeeping for different type of file. PFB scenario.
I have below set of files in a network path(\NAS.domain.local\data\Arasan)
test.sql
test1.txt
test2.log
I am trying to rename the files as shown below and move the files to .\Archive\ directory
Test_15-12-2016_151428.sql
Test1_15-12-2016_151428.txt
Test_15-12-2016_151428.log
([Filename]_DD-MM-YYYY_HHMISS.[ext])
I have built the below batch script.
#echo ON
SET Log_Path=\\NAS.domain.local\data\Arasan
SET Script_Path=C:\Scripts
REM ###########################################REM
REM ## Do make any changes to the text below ##REM
REM ###########################################REM
cd %Script_Path%
pushd %Log_Path%
dir /b /a-d > %Script_Path%\list.txt
set HH=%TIME:~0,8%
for /F %%A in (%Script_Path%\list.txt) do (
setlocal EnableExtensions EnableDelayedExpansion
set ffname=%%A
set "fname=%%~nA"
set "fext=%%~xA"
ren !ffname! !fname!_%DATE%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%!fext!
endlocal
)
del %Script_Path%\list.txt
move *.* Archive\
popd
exit
Now my issue is it is working perfectly in my machine but when I transfer this to server and execute. It is
throwing "The syntax of the command is incorrect." Error.
And it is moving the files without renaming. As for as i know, file name and extension is not being assigned to the variable properly in below part
set ffname=%%A
set "fname=%%~nA"
set "fext=%%~xA"
Server OS: Windows server 2008 R2 Standard(SP1)
Can anyone please help me. Thanks a lot.
Here is the part of the code you should be using to get a consistent date and time output:
For /F "Skip=1" %%A In ('WMIC OS GET LocalDateTime') Do For %%B In (%%~nA
) Do Set "DTS=%%B"
Set "DTS=_%DTS:~6,2%-%DTS:~4,2%-%DTS:~,4%_%DTS:~-6%"
Echo( [%DTS%]
Pause
Just incorporate this into the rest of your codeā¦
I have a Batch script where I want to move the files from one folder to another. But the challenge here is the name of the folder where I am moving the file to changes based on date also file name changes based on current date e.g. date_file_name. I tried this approach,
#ECHO OFF
for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
set dow=%%i
set month=%%j
set day=%%k
set year=%%l
)
set day=%month%%day%%year%
echo %day%
set f_name=BulkScript.sh
echo %f_name%
echo "Renaming the downloaded script...."
ren %f_name% %day%_%f_name%
echo "Move the file"
move C:/Users/Downloads/%day%_%f_name% C:/Users/Downloads/%day%/
So I wanna move file from Downloads to day folder. The % here gives me error, of course I am new to Batch programming. Any help will be appreciated.
#ECHO OFF
CLS
REM Start Backup
TITLE Backup
SETlocal EnableDelayedExpansion
REM Capture the date/time(right down to the second) and then assign it to a variable
SET yy=%date:~-4%
SET dd=%date:~-7,2%
SET mm=%date:~-10,2%
SET newdate=%dd%%mm%%yy%_%Time:~0,8%
SET newdate=%newdate::=%
SET foldername=svetlana_backup_%newdate%
REM Variables
SET drive=R:
SET sevenZip=%USERPROFILE%\7z.exe
SET destination=R:\Backup
ECHO Running Backup Batch File
ECHO Please Plug in %drive%
PAUSE
ECHO %foldername%
MKDIR %destination%\%foldername%
FOR /F "tokens=1,2 delims=," %%i IN (backuplist.txt) DO (
SET completeSource=%%i
SET completeDestination=%destination%\%foldername%\%%j
ECHO Source: "!completeSource:"=!"
ECHO Destination:"!completeDestination:"=!"
MKDIR "!completeDestination:"=!"
XCOPY "!completeSource:"=!" "!completeDestination:"=!" /E /F
)
REM Zip the folder using the 7z command line utility
%sevenZip% a -tzip %destination%\%foldername%.zip %destination%\%foldername%
REM Remove the unzipped backup folder
RMDIR /Q /S %destination%\%foldername%
PAUSE
EXIT
This is a backup batch file that I've been using for last couple of days. It worked well up until this morning. For some reason, when it creates the variable foldername, it contains a space in the string where there was none before. It ends up like this:
svetlana_backup_22092016_ 93829
The space between the dash and the 93829 was never there before until today for some reason. How would I remove it and prevent it from happening again?
You can parse the file-/foldername like this
set foldername=%foldername: =%
This will replace all spaces with an empty string
The problem was likely caused because the test was run at a time where the hour contained just one digit. With that %Time:~0,8% will output the time including an extra space, as the time will be stored like this: 9:38:29 which are 7 characters and you read the last 8 ones.
What's a batch script command to touch on a file to update its date and time to the current date and time? (Modified Date)
For example, Joe Blow sends me a text document which he created months ago, when he emails me the document, I want to keep track of how old it is from the day I received it (not when he created it) so I want to update the file's date/time to the current date/time.
I have a batch script to automatically weed out files that haven't been edited within 90 days, so this is troublesome when I receive a particularly older file then all of a sudden it disappears.
And I need it via a batch script as I have hundreds of files to manage, and it's for archiving files.
I can't take all the credit, but I did look through my todo.txt to find it
Microsoft "touch" it's a KB article from like 5 years ago
The jist of it is you use copy /b MYFILENAME +,, where MYFILENAME is your file
This is an expansion on aflat's anwer.
1) Microsoft support provides an explanation and simple touch.bat script.
2) My custom touch.cmd, which expands on the MS script by including "touch /?" help text.
3) My custom midastouch.cmd, which provides several options including recursive operation and date operations.
As aflat wrote, the simple answer is:
copy /b FILENAME +,,
As you might expect, FILENAME can include relative or absolute path and wildcards like *.txt.
1. Microsoft1 support:
The following MS-DOS command updates the date and time stamps of a
file named "EXAMPLE" without altering the contents of the file. This
is similar to the TOUCH utility found in XENIX and in some third-party
MS-DOS toolkits.
COPY /B EXAMPLE +,,
The COPY command can concatenate a file onto an existing file when
used in the form:
COPY FILE1+FILE2
In this example, the contents of FILE2 are appended to FILE1, leaving FILE2 unchanged. When copying in this mode, the COPY command
switches to ASCII mode where the ^Z (0x01A) end-of-file marker is
honored.
Therefore, with the above command, the /b forces the COPY command into
binary mode, the filename is the file to be updated, the + (plus sign)
indicates that a file is to be appended, and the ,, (commas) are
placeholders for the remaining parameters (which are not included in
this example). Because the file to be appended is not specified, the
COPY command will append nothing and only update the time and date
stamps for the file.
The following batch file, TOUCH.BAT, can be used to automate the
process:
#echo off
if %1.==. goto end
if not exist %1 goto end
copy /b %1 +,, > nul
echo %1 touched!
:end
This batch file requires one parameter, the file to be "touched." If the
parameter is not supplied, line 2 will cause the batch file to
exit without doing anything. If the specified file does not exist,
line 3 will cause the batch file to exit also.
2. Touch.cmd
#echo off
:: -----------------------------------------
:: Process input parameter
:: -----------------------------------------
: Help requestes?
if "%1%"=="/?" goto help
if "%1%"=="?" goto help
if "%1%"=="" goto help
:: -----------------------------------------
:: Update Modified Date property to now
:: -----------------------------------------
if not exist %1% goto end
copy /b %1% +,, > nul
echo %1 touched!
goto end
:help
#echo off
echo :: --------------------------------------------------------------
echo :: Touch.cmd Help
echo :: --------------------------------------------------------------
echo.
echo Touch.cmd is batch script to update the Modified Date property
echo of teh specified file to the current
echo date and time.
echo.
echo Syntax: touch filename
echo where,
echo filename is the name of the name of the file to "touch."
echo filename may include a relative o full path.
echo filename may include wild cards like *.txt.
echo.
:end
3. MidasTouch.cmd
#echo off
:: -----------------------------------------
:: Find files older than specified date
:: -----------------------------------------
:: -----------------------------------------
:: Default Values
:: -----------------------------------------
set "default_path=%cd%"
set "default_err_log=%cd%\midastouch_err.log"
set /a default_date=-365
set "open_log=False"
set "recurse=True"
:: -----------------------------------------
:: Process input parameters
:: -----------------------------------------
: Help requestes?
if "%1%"=="/?" goto help
if "%1%"=="?" goto help
if /I "%1%"=="help" goto help
set "dir_in="
set "err_log="
set "dd="
:: Read in commandline arguements.
echo Arguements:
:arguement_loop
if "%1%"=="/p" (
echo Path: %2%
set dir_in=%2%
shift
goto loop_bottom)
if "%1%"=="/l" (
echo Error log: %2%
set err_log=%2%
shift
goto loop_bottom)
if "%1%"=="/-l" (
echo No error log. Output to console.
set err_log=CON
shift
goto loop_bottom)
if "%1%"=="/d" (
echo Date: %2%
set /a dd=%2%
shift
goto loop_bottom)
if "%1%"=="/o" (
echo Open log: True
set "open_log=True"
goto loop_bottom)
if "%1%"=="/-o" (
echo Open log: False
set "open_log=False"
goto loop_bottom)
if "%1%"=="/s" (
echo Recursive: True
set "recurse=True"
goto loop_bottom)
if "%1%"=="/-s" (
echo Recursive: False
set "recurse=False"
goto loop_bottom)
if not "%1%"=="" (
if "%dir_in%"=="" (
echo Path: %1%
set dir_in=%1%
goto loop_bottom)
if "%err_log%"=="" (
echo Error log: %1%
set err_log=%1%
goto loop_bottom)
if "%dd%"=="" (
echo Date: %1%
set /a dd=%1%
goto loop_bottom)
)
:loop_bottom
shift
if not "%1%"=="" goto arguement_loop
if "%dir_in%"=="" (
set dir_in=%default_path%)
if "%err_log%"=="" (
set err_log=%default_err_log%)
if "%dd%"=="" (
set /a dd=%default_date%)
:: -----------------------------------------
:: Execution
:: -----------------------------------------
:: Write header
set "header=Touch_dir.cmd Error Log"
if exist %err_log% (
del /q %err_log%)
#echo %header% >%err_log%
set cmd_str="cmd /c copy /b #path +,,"
:: Update Modified Date property to now
if /I "%recurse%"=="True" (
set cmd_str=forfiles /s /p %dir_in% /d %dd% /c %cmd_str%
) else (
set cmd_str=forfiles /p %dir_in% /d %dd% /c %cmd_str%
)
echo Command: %cmd_str% >>%err_log%
echo Errors: >>%err_log%
echo. >>%err_log%
echo Executing command: %cmd_str%
#echo Updating Modified Date of files older than date: %dd%.
#echo This may take a while. Please be patient...
#echo.
echo.
set cmd_str=%cmd_str% || #echo Failed to update: #path >>%err_log%"
%cmd_str%
:: Results
#echo Error log: %err_log%
if "%open_log%"=="True" (start %err_log%)
goto end
:help
#echo off
echo :: --------------------------------------------------------------
echo :: Touch_dir.cmd Help
echo :: --------------------------------------------------------------
echo.
echo Touch.cmd is batch script to recursively "touch" all files in a
echo folder to update their Modified Date property to the current
echo date and time.
echo.
echo Syntax: touch_dir /d directory /l err_log /m months
echo where,
echo /p path Path containing files with Modified
echo Date values to update to now.
echo (default = current directory).
echo /s (or /-s) Recursive (or not recursive) search
echo (default recursive is %recurse%).
echo /l err_log Error log: list of files not updated
echo (default err_log: midastouch_err.log).
echo /o (or /-o) Open (or do not open) error log after
echo execution (default open_log: %open_log%).
echo /d date Selects files with a last modified date greater
echo than or equal to (+), or less than or equal to
echo (-), the specified date using the
echo "MM/dd/yyyy" format; or selects files with a
echo last modified date greater than or equal to (+)
echo the current date plus "dd" days, or less than or
echo equal to (-) the current date minus "dd" days. A
echo valid "dd" number of days can be any number in
echo the range of 0 - 32768.
echo "+" is taken as default sign if not specified.
echo (default date is: %default_date%).
echo.
:end
Just to add that the same source provide a batch script.
#echo off
goto start
:usage
echo usage: TOUCH.BAT "MYFILENAME"
exit /b 0
:start
if %1.==. goto usage
if not exist %1 goto usage
copy /b %1 +,, > nul
echo %1 touched!
exit /b 0