How to control task scheduler avoiding to replace account

Luciano Colombo 20 Reputation points
2023-06-13T13:56:43.0633333+00:00

using Microsoft.Win32.TaskScheduler;

When I try to stop, run, enable and disable a scheduled task, I must do a new Task registration

task.Definition.Settings.Enabled = true; taskService.RootFolder.RegisterTaskDefinition(task.Path, task.Definition, TaskCreation.Update, opts.username);

In this way changes the account with the task is registered.

I wonder if I could control the scheduled task using a properly granted account but avoiding to replace the already stored account

Developer technologies C#
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2023-06-13T20:33:03.62+00:00

    You can just run/stop/enable directly on task rather than on task.Definition.Settings. The latter is more for providing a default configuration when initially registering the task. If the task already exists and you're just trying to interact with the active instance then you can query for it via the TaskService:

    var task = taskService.RootFolder.GetTasks().First(t => t.Name == "Test");
    
    // To enable/disable
    task.Enabled = true;
    
    // Or to run
    task.Run();
    
    // Or to stop
    task.Stop();
    

    Setting Enabled or calling Run or Stop will immediately affect the active instance and don't need you to re-register the task with the updated definition.

    I believe RegisterTaskDefinition is just needed if you want to update the task definition but not the active instance.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.