[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Once a day batch file

Posted on 2009-02-12
26
Medium Priority
?
1,412 Views
Last Modified: 2012-05-06
Does anyone have a batch file or template for one that will only run the script once per day regardless of how many times the batch is called? I've read the way most users do this is by creating another file and then checking the date on the file to see if the script should run again. That seems like a good way to me I just don't know enough scripting to do it myself.

Any help would be appreciated.
Thanks,
Steve
0
Comment
Question by:smandell
  • 6
  • 5
  • 4
  • +3
24 Comments
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 23625885
echo off
set file=.\%date:~4,2%-%date:~7,2%-%date:~10,4%.txt
if exist %file% goto quit
echo n1>%date:~4,2%-%date:~7,2%-%date:~10,4%.txt

REM code goes HERE.
:quit
echo File already launched today.
pause
0
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 23625894
cleaned up batch:

echo off
set file=.\%date:~4,2%-%date:~7,2%-%date:~10,4%.txt
if exist %file% goto quit
echo n1>%file%

REM code goes HERE.
:quit
echo File already launched today.
set file=
pause
0
 
LVL 21

Expert Comment

by:AmazingTech
ID: 23625900
Give this a try.
for /f %a in ('dir /b datefile.txt') do echo %~ta | find "%date:~-10%"
if not errorlevel 1 GOTO :EOF
 
{insert your code here}
{insert your code here}
{insert your code here}
 
::Update the modified date/time of the datefile.txt
echo Batch file ran>>datefile.txt

Open in new window

0
Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

 
LVL 13

Expert Comment

by:dhoffman_98
ID: 23625962
Without writing too much code to check file dates and comparing them to something dynamic, what you could do is have your batch file create a "flag" file somewhere on your disk. Then when the batch file runs, have it check for the existence of the flag file and only continue if it does not exist.

For example:
if not exist c:\flag.txt...

The last part of your batch file should be to then create that file so that if the batch is run again, it will just quit.

Then create a scheduled task that runs each night at midnight that deletes the file if it exists.
0
 

Author Comment

by:smandell
ID: 23627793
I started testing ged's code since it was the first to come in and it seems to be working well. What's the difference between ged's and AmazingTech's solution?

Do either of those scripts allow me to adjust a parameter in the code to specify how many days must go by before the script will execute. I realize that wasn't an original requirement but now i'm thinking of a few other uses.

I don't think dhoffman's suggestion will work for me because the script will be running on remote laptops with no guarantees as to when they will be on and available to run the scheduled task.

Thanks.
0
 
LVL 21

Expert Comment

by:AmazingTech
ID: 23628064
ged is creating a marker file with todays date. Tomorrow there will be yesterday's and current date. Date files will grow and grow. Probably should put in a clean up routine.

Mine at the end of the script it updates the 1 file datefile.txt after your code runs. When the batch runs again it checks the datefile.txt last modified date for today's date. Probably should change my last line to

echo Batch file ran %date%>datefile.txt

so the size doesn't grow.
0
 
LVL 21

Expert Comment

by:AmazingTech
ID: 23628073
Days gone by can be put in too but you'll need additional code and let me know your date format.

echo %date%
0
 

Author Comment

by:smandell
ID: 23628106
I see, good idea.
My date format: Thu 02/12/2009
Thanks!
0
 
LVL 21

Assisted Solution

by:AmazingTech
AmazingTech earned 600 total points
ID: 23628276
Try this out.

Modify the DaysAgo to suit your needs.

Also we can specify a full path to where you want to store the datefile.txt if you want it other than the current working directory.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
 
Set DaysAgo=7
 
call :SubDays %DaysAgo%
 
if exist datefile.txt for /f "tokens=1,2,3,6,* delims=/ " %%a in ('dir datefile.txt ^| find "/"') do If %%c%%a%%b GEQ %Year%%Month:~-2%%Day:~-2% ECHO Batch file was not run more than %DaysAgo%. Exiting.. & GOTO :EOF
 
ECHO {insert your code here}
ECHO {insert your code here}
ECHO {insert your code here}
PAUSE 
 
::Update the modified date/time of the datefile.txt
echo Batch file ran %date%>datefile.txt
 
 
goto :EOF
 
:SubDays
Set DaysInMonth=31,28,31,30,31,30,31,31,30,31,30,31
 
Set Year=%date:~-4%
Set Day=1%date:~-7,2%
Set Month=1%date:~-10,2%
 
Set /a Day-=%1
:FixDay
If !Day! LEQ 100 (
    Set /a Month-=1
    if !Month! == 100 (
        Set /a Year-=1
        Set Month=112
    )
    Set MCounter=101
    Set DaysInThisMonth=
 
    for %%d in (%DaysInMonth%) do if not defined DaysInThisMonth if !MCounter! == !Month! (Set DaysInThisMonth=%%d) else (Set /a MCounter+=1)
 
    if !Month! == 102 (
        if %Year:~-2% == 00 (
            Set /a Mod=!Year:~0,2! %% 4
            if !Mod! == 0 Set /a DaysInThisMonth+=1
        ) else (
            Set /a Mod=!Year! %% 4
            if !Mod! == 0 Set /a DaysInThisMonth+=1
        )
    )
    Set /a Day+=!DaysInThisMonth!
)
If !Day! LEQ 100 GOTO FixDay
GOTO :EOF

Open in new window

0
 
LVL 16

Expert Comment

by:t0t0
ID: 23629966
Apologies for coming in on this one so late however, I couldn't help mentioning my own preferre method which does use the creation of a file.

Personally, I would prefer to make proper use of Windows' registry file. For example, name the following code RUNSCRIPT.BAT

Next, create a (string value) entry in the RUN section of the registry file such as:

   HKLM\Software\Microsoft\Windows\CurrentvVersion\Run\MyApplication

and set it's value pointing to the full path of this batch file such as:

   "C:\Batch\RunScript.bat"

Now everytime the Windows is re-started this batch file will run.

This abtch file will only run your script file once a day whether you run this batch file from the command line, from within another script or from the registry file itself.

This batch file uses a key in the application data section of the registry file to determine whther or not your application has run during the current day.



@echo off
set MyAppName=MyApplication
 
reg query hkcu\software\%myapp% /v LastRun > NUL 2>&1
if not %ERRORLEVEL%==0 reg add hkcu\software\%MyAppName% /v LastRun /t reg_expand_sz /d 00/00/0000 > NUL
 
for /f "skip=4 tokens=3" %%r in ('reg query hkcu\software\%MyAppName% /v LastRun') do set lastrun=%%r
 
if not "%lastrun%"=="%date%" (
   reg add hkcu\software\%MyAppName% /v LastRun /t reg_expand_sz /d %date% /f > NUL
   echo start script
)

Open in new window

0
 
LVL 16

Expert Comment

by:t0t0
ID: 23629983
Oh, I forgot to mention...

To use the batch file... changes:

   set MyAppName=MyApplication

to the name of your application and edit,,

   echo start script

to whatever is required to run you script


0
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 23632601

echo off
set file=.\%date:~4,2%-%date:~7,2%-%date:~10,4%.txt
if exist %file% goto quit
REM Delete old text files per suggestions
del *.txt
echo n1>%file%

Also t0t0 . . . depending on the system, there is a chance that the registry will be locked down.

REM code goes HERE.
:quit
echo File already launched today.
set file=
pause
0
 
LVL 41

Accepted Solution

by:
Kyle Abrahams earned 800 total points
ID: 23632610
REM: comment was in middle of code.
echo off
set file=.\%date:~4,2%-%date:~7,2%-%date:~10,4%.txt
if exist %file% goto quit
REM Delete old text files per suggestions
del *.txt
echo n1>%file%

REM code goes HERE.
:quit
echo File already launched today.
set file=
pause

Also t0t0 . . . depending on the system, there is a chance that the registry will be locked down.
0
 
LVL 13

Expert Comment

by:dhoffman_98
ID: 23632727
I do like some of the other examples shown on here, but I'll add a comment to the author regarding not being sure when the machines are online.

Scheduled tasks CAN be configured so that they execute the next time the machine is on if the schedule was missed. So if it was to execute at midnight, but the machine was off, then next time the machine is turned on, it will still execute.
0
 
LVL 39

Expert Comment

by:BillDL
ID: 23645188
I am fully aware that this is the DOS topic area, but I would tend to agree with dhoffman on this.  Seeing as you only want the batch file to be run once a day, do you really need the batch file to test if it has already been run?  I suppose it all depends on what programs, processes, or user activities may make an unwanted call to run the batch file at any time.  Only you will know the likelihood of that possibility.

For what it's worth, I use a small program to do my "Once a Day" tasks.  It may do just what you need:
http://www.karenware.com/powertools/ptoad.asp

If not, then you have enough batch scripts here for any occasion, ranging from the simple and effective "flag file", to the startup program to check registry values.
0
 
LVL 16

Assisted Solution

by:t0t0
t0t0 earned 600 total points
ID: 23645513
Oops! Spotted a mistake....

This will process everything else after the REM statement if this batch file has not already run today.

As an improvement, I've named the registry key the same name you decide to call this batch file. This means you can copy & paste and run straight away....

See how nice I am to you.....
:
@echo off
set MyAppName=%0
 
reg query hkcu\software\%MyAppName% /v LastRun > NUL 2>&1
if not %ERRORLEVEL%==0 reg add hkcu\software\%MyAppName% /v LastRun /t reg_expand_sz /d 00/00/0000 > NUL
 
for /f "skip=4 tokens=3" %%r in ('reg query hkcu\software\%MyAppName% /v LastRun') do set lastrun=%%r
 
if "%lastrun%"=="%date%" (exit /b) else (reg add hkcu\software\%MyAppName% /v LastRun /t reg_expand_sz /d %date% /f > NUL)
 
rem =========== Continue to process rest of batch file ===========
:

Open in new window

0
 

Author Comment

by:smandell
ID: 23662182
Wow, this is the best response I've ever gotten on Experts-Exchange. Thanks!

I think I have enough scripts and suggestions here to last for a while. Just to clarify, for those suggesting alternatives to scripts like registry or scheduled tasks the reason I need a script is because I want it to run the first time a user logs onto the VPN remotely each day. The script will actually be on a remote server so I have one file to update for all vpn users. It's always been an issue for me that only users that come into the office run login scripts, this has all been about applying that to remote user as well.

I'm just going to test a few of these out then close the question.

Thanks again.
0
 
LVL 16

Expert Comment

by:t0t0
ID: 23709956
This technique uses ADS....

@echo off

(for /f %%a in (%~nx0:LastRun) do set LastRun=%%a) 2>>nul
if "%LastRun%"=="" set LastRun=00/00/0000
if "%LastRun%"=="%date%" (exit /b) else (echo %date%>%~nx0:LastRun)

rem =========== Continue to process rest of batch file ===========

echo Running...
0
 
LVL 16

Expert Comment

by:t0t0
ID: 23725702
Just to add a final variation to my code above and my earlier code using the registry file. This example is more down to earth and one which you will find easier to understand. It basically saves the LastRun date to an external file and reads it in each time the batch file runs, comparing it to the current date. If the current date is different, then it upfates the date i the file. The principle is the same - just another method. Please see code below.

@echo off

if not exist lastrun.txt echo 00/00/0000 > lastrun.txt
(for /f %%a in (lastrun.txt) do set LastRun=%%a) 2>>nul
if "%LastRun%"=="%date%" (exit /b) else (echo %date%>lastrun.txt)

rem =========== Continue to process rest of batch file ===========

echo Processing....
0
 
LVL 16

Expert Comment

by:t0t0
ID: 23730303
smandell

Could you please look at the last few comments and decide if you are satisfied with the solutions given and close this question.

Thank you.
 
0
 
LVL 39

Expert Comment

by:BillDL
ID: 24612697
I would rather not be included in the points split because my comment did not actually answer the question as asked.  I merely posed the rhetorical question suggesting that the asker consider whether or not a batch file was really necessary for the task, and offered an alternative non-DOS suggestion.
0
 

Author Comment

by:smandell
ID: 24613149
Sorry for abandoning the question. I'll close it out. Amazing Tech and T0t0's responses were most helpful.
0
 

Author Closing Comment

by:smandell
ID: 31546256
GED was actually the first to respond with a solution that worked for me but the others contributed useful scripts as well. Thanks all.
0
 
LVL 39

Expert Comment

by:BillDL
ID: 24614300
Thanks for that scathing attack Lee ;-)

"... most of the comments I've seen from you over these many years have been so lengthy and detailed that they could favorably be compared to a Reader's Digest version of Leo Tolstoy's War and Peace".

You know, that's one book I have never had the time to read.  I've always been too busy here .... typing!  :-)
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Issue: Unstable cursor in Windows XP and Windows runs extremely slow in that any click will bring up the Hour glass (sometimes for several seconds before giving you what you want) . Troubleshooting Process and the FINAL FIX: This issue see…
Sometimes people don't understand why download speed shows differently for Windows than Linux.Specially, this article covers and shows the solution for throughput difference for Windows than a Linux machine. For this, I arranged a test scenario.I…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Suggested Courses
Course of the Month19 days, 10 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question