OK. You want to run a command a certain way if it is between 9 AM and 12 PM. You want to run it a different way if it is between 12 PM and 3 PM. How do you accomplish this with a batch file?
The answer is nested IF statements and the %time% system variable. The %time% variable stores the time in a 24 hour format including hour, minute, second and millisecond:
This represents 9:02 AM at 45.80 seconds into the minute. I prefer to work with just the hour in situations like this. So I create a variable called %hour% for such batch files using the following command:
The following shows this operation at the Windows command line:
It is also important to know that you have operator keywords used with the IF statements. They are as follows:
- EQU – equal
- NEQ – not equal
- LSS – less than
- LEQ – less than or equal
- GTR – greater than
- GEQ – greater than or equal
Using these keywords can be simpler to read than the traditional == or != operator types for the uninitiated who read your batch file.
With this in mind, the following batch file code will allow you to test for the hour range and run commands only during specified hours:
@ECHO OFF SET hour=%time:~0,2% IF %hour% GEQ 9 IF %hour% LEQ 12 (GOTO RUNIT) ECHO Wrong time to run! GOTO END :RUNIT ECHO Right time to run! :END
Hopefully this helps you in such scenarios.