批处理文件:如果启用了计划任务,则执行某些操作

batch file: if scheduled task is enabled then do something

我很难弄清楚如何做到这一点。我需要制作一个批处理文件,根据是否启用计划任务,做出相应的反应。我可以使用 schtasks 来查询任务并看到它被禁用但不知道从那里做什么。我可以用某种方式 grep 结果吗?

批处理文件基本上是 "if task is enabled, do this, if it is disabled, do that"。

没有准确的答案,但是有在线帮助,网上有很多关于此类问题的信息。例如,here

C:\Scripts>schtasks /?

SCHTASKS /parameter [arguments]

Description:
 Enables an administrator to create, delete, query, change, run and
 end scheduled tasks on a local or remote system.

Parameter List:
 /Create         Creates a new scheduled task.

 /Delete         Deletes the scheduled task(s).

 /Query          Displays all scheduled tasks.

 /Change         Changes the properties of scheduled task.

 /Run            Runs the scheduled task on demand.

 /End            Stops the currently running scheduled task.

 /ShowSid        Shows the security identifier corresponding to a scheduled task name.

 /?              Displays this help message.

Examples:
 SCHTASKS
 SCHTASKS /?
 SCHTASKS /Run /?
 SCHTASKS /End /?
 SCHTASKS /Create /?
 SCHTASKS /Delete /?
 SCHTASKS /Query  /?
 SCHTASKS /Change /?
 SCHTASKS /ShowSid /?

给你:

rem Set task name
set TASKNAME=My task

rem Get task status
for /f "tokens=2 delims=:" %%i  in ('schtasks /Query /TN "%TASKNAME%" /FO LIST ^| findstr "Status:"') do (set STATUS=%%i)

rem Strip spaces from task status
set STATUS=%STATUS: =%

rem Compare task status...
if /i %STATUS%==Disabled (
echo Task "%TASKNAME%" is disabled
)

if /i %STATUS%==Enabled (
echo Task "%TASKNAME%" is enabled
)

参考文献:

  • How to split command output in Windows command prompt?
  • Removing spaces from a variable in batch
  • Assign Command output to Variable in Batch file
  • IF - Conditionally perform a command