List Windows scheduled tasks with Python
Asked Answered
C

0

7

I am trying to list all scheduled tasks on Windows with a Python script.

On this post, Python check for Completed and failed Task Windows scheduler there is some code which worked.

import win32com.client

TASK_STATE = {0: 'Unknown',
              1: 'Disabled',
              2: 'Queued',
              3: 'Ready',
              4: 'Running'}

scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect()

folders = [scheduler.GetFolder('\\')]
while folders:
    folder = folders.pop(0)
    folders += list(folder.GetFolders(0))
    for task in folder.GetTasks(0):
        print('Path       : %s' % task.Path)
        print('State      : %s' % TASK_STATE[task.State])
        print('Last Run   : %s' % task.LastRunTime)
        print('Last Result: %s\n' % task.LastTaskResult)

However, I would like to display the path of the file it executes (e.g. c:\test\aaa.bat) and the parameters of the command. How could this be done?

And could anyone explain the meaning of some commands in the code:

  1. [] in the code "[scheduler.GetFolder('\')]"
  2. Where could I get the detail explaination of code like list(folder.GetFolders(0)), folder.GetTasks(0)? Is there any documentation available?
Cuss answered 4/9, 2017 at 13:31 Comment(4)
Use the provided links. Dispatch returns an ITaskService instance. GetFolder('\\') returns an ITaskFolder for the root folder in the scheduler namespace. GetFolders(0) returns the subfolders in an ITaskFolderCollection. GetTasks(0) gets the non-hidden tasks in the folder in an IRegisteredTaskCollection. To include hidden tasks, use GetTasks(TASK_ENUM_HIDDEN), i.e. GetTasks(1). Enumerating this returns the task as an IRegisteredTask. Note that its Definition property is an ITaskDefinition.Smallish
@eryksun Thanks! I noticed you are also the author of the code of the link, it really helps! '[]' usually is used for list, what is the purpose here?Cuss
There's nothing special. It's just traversing the task tree using a list and a loop. It starts with the root folder in the list. The loop pops a folder; pushes all of its subfolders; and lists the tasks in the folder. It continues until the list is empty. It could be generalized into an os.walk style generator function that yields the path, subfolders and tasks in each folder.Smallish
I added a walk_tasks generator function to my answer on the linked question.Smallish

© 2022 - 2024 — McMap. All rights reserved.