Search code examples
pythonscheduled-taskspywin32

python file from task scheduler as system


I have created a python script to monitor the current version of MS Edge. When run, the script creates a .txt file called previous_version.txt and writes the version number in the text file. This works well when I run the file manually.

Now I'm trying to add this script to task scheduler and add it as a system task for it to run when I'm not logged in (It's supposed to run remotely on a server PC). This however, does not work. It claims that task scheduler has completed the task successfully, but ends with a return code 2147942401 and never creates a .txt file.

Please see attached pictures below.

enter image description here

enter image description here

My python script:

import os
import win32api

def local_has_changed():
    filepath = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
    info = win32api.GetFileVersionInfo(filepath, "\\")
    ms = info["FileVersionMS"]
    new_majorversion = str(win32api.HIWORD(ms))

    path = os.path.dirname(__file__)
    file = str(path)+"\\previous_version.txt"

    if not os.path.exists(file):
        open(file, 'w+').close()
        
    filehandle = open(file, 'r')
    old_majorversion = str(filehandle.read())
    filehandle.close()
    
    if new_majorversion != old_majorversion:
        print('Version changed from '+old_majorversion+' to '+new_majorversion)

    filehandle = open(file, 'w')
    filehandle.write(str(new_majorversion))
    filehandle.close()

local_has_changed()

The file runs well manually on both the remote server and my local pc, but task scheduler fails on both. I'm running Windows 11


Solution

  • I finally figured it out.

    Even though pywin32 was listed in the pip list in elevated cmd, system did not have access to pywin32.

    The fix was simply reinstalling pywin32 in elevated cmd, and now everything works as it's supposed to!