Batch file to delete a Scheduled Task

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
jason76
Posts: 2
Joined: 26 Aug 2014 11:28

Batch file to delete a Scheduled Task

#1 Post by jason76 » 26 Aug 2014 11:41

I am trying to delete a scheduled task on Windows 7 computers if it exists. I found this online but can't get it to work for me. I need the script to delete the task if it exists and if it does not exist to exit the batch file without trying to delete it. Right now it is trying to delete it whether or exists or not so when it is does not exist it gives a "ERROR: The system cannot find the file specified" which is messing up another process I have going on.

Code: Select all

schtasks /query > app
findstr /B /I "AppleSoftwareUpdate" app > nul
if %errorlevel%==0 goto delete
goto exit

:delete
schtasks /DELETE /TN "AppleSoftwareUpdate" /F > nul

:exit
exit

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: Batch file to delete a Scheduled Task

#2 Post by Squashman » 26 Aug 2014 12:18

If you know the task name why not use that in your query?

Code: Select all

H:\>schtasks /query /tn xdbstart >nul 2>&1

H:\>echo %errorlevel%
0

H:\>schtasks /query /tn xdbstar >nul 2>&1

H:\>echo %errorlevel%
1

Samir
Posts: 384
Joined: 16 Jul 2013 12:00
Location: HSV
Contact:

Re: Batch file to delete a Scheduled Task

#3 Post by Samir » 26 Aug 2014 14:41

jason76 wrote:I am trying to delete a scheduled task on Windows 7 computers if it exists. I found this online but can't get it to work for me. I need the script to delete the task if it exists and if it does not exist to exit the batch file without trying to delete it. Right now it is trying to delete it whether or exists or not so when it is does not exist it gives a "ERROR: The system cannot find the file specified" which is messing up another process I have going on.

Code: Select all

schtasks /query > app
findstr /B /I "AppleSoftwareUpdate" app > nul
if %errorlevel%==0 goto delete
goto exit

:delete
schtasks /DELETE /TN "AppleSoftwareUpdate" /F > nul

:exit
exit
It sounds like your if test is not working correctly. Check the errorlevels for findstr. It may work the opposite of other commands.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Batch file to delete a Scheduled Task

#4 Post by foxidrive » 27 Aug 2014 03:11

Assuming your commands are right, this will work as you need.

The && only executes when the AppleSoftwareUpdate term is found.

Code: Select all

schtasks /query | findstr /B /I "AppleSoftwareUpdate" >nul && schtasks /DELETE /TN "AppleSoftwareUpdate" /F > nul

jason76
Posts: 2
Joined: 26 Aug 2014 11:28

Re: Batch file to delete a Scheduled Task

#5 Post by jason76 » 28 Aug 2014 11:40

Thanks foxidrive that worked perfectly. No more errors if it doesn't exist and the rest of the process finishes without throwing errors.

Post Reply