2

I need to check the status of a Windows scheduled task using python, verifying it by the name of the task. I basically want to know if the task is running or not.

I've searched for an answer but I didn't find any.

How can I do that?

Edit: Based on the comments below, the best way to achieve this AND to have the result in some kind of variable (checking if the State is 'Running', for instance) is this:

"Running" in check_output(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", '-Command', '&{Get-ScheduledTask -TaskPath \* | where taskname -eq "TaskName" | select state;}'])

1 Answers1

2

You can use the subprocess module.

import subprocess

subprocess.call(r'schtasks.exe /query  /tn "TASKNAME_HERE"', shell=True)

If you get access denied, may need to change string to pass server address and credentials like so:

import subprocess

subprocess.call(r'schtasks.exe /query /S 192.168.1.100 /u domain\username /P pass /tn "TASKNAME_HERE"', shell=True)

As discussed below, to get only the "state" of the command, it is easy to use powershell. Try this:

import subprocess

subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", '-Command', '&{Get-ScheduledTask -TaskPath \* | where taskname -eq "Ajustar Inventario SM" | select state;}'])

This will return:

State
-----
Ready
Narzard
  • 3,840