python file from task scheduler as system

48 Views Asked by At

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

2

There are 2 best solutions below

0
Martin On BEST ANSWER

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!

5
OldBoy On

The returned value you see equates to System Error code 80070001. And the description for that is:

Severity: 2 - Warning
Facility: 7 - FACILITY_WIN32
Error: 0001 - Incorrect function.

But it is not clear which function it refers to. It may be that running this code under the SYSTEM account is preventing access to some feature or file. You will need to add some debug code to try and diagnose it. Also check that the location of the script and any files it refers to, are within directories that the system can access.