Search code examples
c++windowstaskscheduler

Task Scheduler : Access Denied when setting RunLevel


The problem is all in the title. I am trying to register a task to be run in the system task scheduler. When I comment this part of my code :

HRESULT hr = taskDefinition->get_Principal(&taskSecuritySettings);
if (SUCCEEDED(hr))
    hr = taskSecuritySettings->put_RunLevel(TASK_RUNLEVEL_HIGHEST);

The task registration works as expected. If I uncomment it, it fails with the "Access is denied" error. Here is the code for task registration:

   const HRESULT hr = taskFolder->RegisterTaskDefinition(
      _bstr_t(defaultTaskName), taskDefinition,
      TASK_CREATE_OR_UPDATE, username, password,
      logonType,
      _variant_t(L""),
      registeredTask
   );

where logon type is usually TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD. Changing it to TASK_LOGON_PASSWORD or TASK_LOGON_INTERACTIVE_TOKEN did not change anything.

The user/password I am providing is a local administrator. Using administrator account gives the same results. Using no user/password and TASK_LOGON_NONE gives the same results.

Any ideas?


Solution

  • The problem was not in the API use, it was in the executable rights. In order to run it with TASK_RUNLEVEL_HIGHEST successfully, it has to be executed as Administrator.

    This behaviour can be found in Microsoft documentation : https://learn.microsoft.com/en-us/windows/desktop/taskschd/security-contexts-for-running-tasks