'Adding Principal.RunLevel to Task Scheduler on Python using win32com
After looking around the internet for many days. I've decided to ask my own question. I've done some digging around and found some ways to implement this but i'm stuck. I know that i have to change the logon_type and set the username but it doesn't seem to work. I've tried using the salt.module.win_task.py as a guideline but it still doesn't work for me. This is my code (borrowed from someone else with some tweaks i did)
scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect()
root_folder = scheduler.GetFolder('\\')
task_def = scheduler.NewTask(0)
# Create trigger
start_time = datetime.datetime.now() + datetime.timedelta(minutes=30)
TASK_TRIGGER_TIME = 1
trigger = task_def.Triggers.Create(TASK_TRIGGER_TIME)
trigger.StartBoundary = start_time.isoformat()
# Create action
TASK_ACTION_EXEC = 0
action = task_def.Actions.Create(TASK_ACTION_EXEC)
action.ID = "TEST"
action.Path = "C:/test/test.bat"
action.Arguments = ''
action.WorkingDirectory = "C:/test/"
# Set parameters
task_def.RegistrationInfo.Description = 'Run test.bat'
task_def.Settings.Enabled = True
task_def.Settings.StopIfGoingOnBatteries = False
task_def.Settings.Hidden = False
task_def.Settings.startwhenavailable = True
task_def.Settings.DisallowStartIfOnBatteries = False
# Register task
# If task already exists, it will be updated
TASK_CREATE_OR_UPDATE = 6
TASK_LOGON_NONE = 0
root_folder.RegisterTaskDefinition(
"TEST", # Task name
task_def,
TASK_CREATE_OR_UPDATE,
'', # No user
'', # No password
TASK_LOGON_NONE)
I've tried adding (copying from win_task.py)
TASK_RUNLEVEL_HIGHEST = 1
TASK_LOGON_SERVICE_ACCOUNT = 5
task_def.Principal.UserID = "SYSTEM"
task_def.Principal.DisplayName = "SYSTEM"
task_def.Principal.GroupID = "Administrators"
task_def.Principal.LogonType = TASK_LOGON_SERVICE_ACCOUNT
task_def.Principal.RunLevel = TASK_RUNLEVEL_HIGHEST
and changing this part
root_folder.RegisterTaskDefinition(
"TEST", # Task name
task_def,
TASK_CREATE_OR_UPDATE,
task_def.Principal.UserID,
None, # No password
TASK_LOGON_SERVICE_ACCOUNT)
I've tried almost everything, Does anyone know how to add the runlevel property? (without using XML)
Solution 1:[1]
Your code works great! The reason you are getting the error code:
(-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024891), None)
is because you are trying to change Principal.Runlevel without administrative privileges.
For your code to work, Run a cmd window as Admin and use that to run your win_task.py.
>python win_task.py
Here is a video on how to do that!
I was able to create a task and change the "run with highest privileges" checkbox after I ran the script as admin.
Here is the only resource I was able to find explaining principal.runlevel
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
