Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF exist for scheduled task

I have created a batch file to check if scheduled task exists and if they don't create them, however, my if exist rule seem to always hit true even though the jobs are not there.

Any ideas?

::Check Rule
IF EXIST SchTasks /QUERY /TN "Cache Task Morning"  ( 
    echo ! Morning rule in place!
    GOTO NEXT 
) ELSE IF NOT EXIST SchTasks /Create /SC DAILY /TN "Cache Task Morning" /TR "C:\Cache Clear\Cache Clear.bat" /ST 09:00 

:NEXT
IF EXIST SchTasks /QUERY /TN "Cache Task Afternoon"  ( 
    echo ! Afternoon rule in place!
    GOTO NEXT TWO
) ELSE IF NOT EXIST SchTasks /Create /SC DAILY /TN "Cache Task Afternoon" /TR "C:\Cache Clear\Cache Clear.bat" /ST 15:00 

:NEXT TWO
IF EXIST SchTasks  /QUERY /TN "Cache Task Evening"  ( 
    echo ! Evening rule in place!
    GOTO CLEAR CACHE 
) ELSE IF NOT EXIST SchTasks /Create /SC DAILY /TN "Cache Task Evening" /TR "C:\Cache Clear\Cache Clear.bat" /ST 18:00 
like image 883
Tom Avatar asked Jan 10 '17 13:01

Tom


People also ask

How can I tell if a scheduled task is running?

Windows Scheduled tasks history is written to an event log. If you open Event Viewer and go to: Event Viewer (Local) / Applications and Services Logs / Microsoft / Windows / TaskScheduler / Optional, you will see all the Task Histories.

How can I get a list of scheduled tasks?

To open Scheduled Tasks, click Start, click All Programs, point to Accessories, point to System Tools, and then click Scheduled Tasks. Use the Search option to search for "Schedule" and choose "Schedule Task" to open the Task Scheduler. Select the "Task Scheduler Library" to see a list of your Scheduled Tasks.

Will scheduled task run if not logged in?

To run the task with the option "Run whether user is logged on or not" you have to activate the option "Run with highest privileges". After activating this option the task really run whether the user is logged or not.

How do you trigger a scheduled task?

Go to the Scheduled Tasks applet in Control Panel, right-click the task you want to start immediately, and select Run from the displayed context menu.


1 Answers

You cannot use if exist with schtasks, this is not the purpose of if exist.

use either

schtasks /query /TN "task_name" >NUL 2>&1 || schTasks /Create /SC DAILY /TN "task_name" ...

or

schtasks /query /TN "task_name" >NUL 2>&1
if %errorlevel% NEQ 0 schTasks /Create /SC DAILY /TN "task_name" ...

>NUL 2>&1 suppress success or error output, but we have errorlevel set to 0 if success, or not 0 if failure.

Both are pretty the same. In the first case we use the cmd && and || operators, where && means previous command succesful and || means previous command failed.

as in

mycommand && echo success || echo error

As we only want to test failure, then use only || (previous command failed).

like image 111
elzooilogico Avatar answered Oct 01 '22 12:10

elzooilogico