Run Windows command line scripts by condition

In the Windows command line, it is possible to build loops that periodically execute scripts. You can see how to do that in one of my previous posts. Let’s say you want to run R script from the Windows command line but with a condition or multiple conditions. For example, run R script from the command line only after a specific hour or run between certain hours. Here is how to do that.

Running script from the Windows command line with one condition.

For example, you should run the script only after a specific hour. I’m using a 24 hour time system and if I build condition that script runs only after an hour is greater than 18 it means that script will execute starting from 19th to 24th hour.

CMD if condition looks like this. If the hour is greater then 18, execute R script, but in other case return text some text. After if statement script goes to loop.

If conditions are met, I can see a result like this.

About some of the other code.

For me, additional information is required. For example, date and time for each loop and description. All that goes after an echo command.

To add line break use echo and dot.

You wan to clear the Windows command line every time the new loop starts. Then you have to call cls command.

To comment you can use rem function.

Change the Windows command line date format to YYYY-MM-DD.

Usually to create timestamp you can go with a line like this.

But the result was not satisfying for me.

You may consider going to Windows control panel and change date format in Region and Language settings where it is specified.

Another approach is to do that in batch file with little help of set function and substrings from the original date format. That is what I did in this code. Type set /? in the command line to read more.

Running script from the Windows command line with multiple conditions.

For this purpose, you can use nested if function. In this example script will run if the current hour is greater or equal to 18 and less then 20. Some of the comparing options can be pretty handy. If you type if /? you can get instructions like this:

EQU – equal
NEQ – not equal
LSS – less than
LEQ – less than or equal
GTR – greater than
GEQ – greater than or equal

If I don’t meet conditions result looks like this.

Here is full list of Windows command line commands.

0 comments on “Run Windows command line scripts by condition

Leave a Reply

Your email address will not be published. Required fields are marked *