0

I'm using the TaskService class to create and edit Windows Scheduled Tasks. One problem I have is how to save a new trigger on an existing Scheduled Task. The trigger does not seem to save.

var task = new TaskService().FindTask("My Scheduled Task");
BootTrigger trigger = new BootTrigger();
var td = task.Definition;
//td.Triggers.Count = 1 at this point
td.Triggers.Add(trigger);
//td.Triggers.Count = 2 at this point

So the code seems okay. But if I open the Scheduled Task in Windows, only 1 trigger is shown and not the one I added. If I run my code again, the trigger count is back to 1, so it seems like there should be some Commit() or Save() function. What am I missing?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Cameron Castillo
  • 2,712
  • 10
  • 47
  • 77

1 Answers1

0

You are missing re-registering the task definition.

var ts = new TaskService();
var task = ts.FindTask("My Scheduled Task");
BootTrigger trigger = new BootTrigger();
var td = task.Definition;
//td.Triggers.Count = 1 at this point
td.Triggers.Add(trigger);
//td.Triggers.Count = 2 at this point
ts.RootFolder.RegisterTaskDefinition("My Scheduled Task", td);
Royi Mindel
  • 1,258
  • 12
  • 35
  • Thanks. I'm getting a "Access is denied." exception on the RegisterTaskDefinition command. I can create the task and 1st trigger successfully with code without this error. But at least I have something else to struggle with now. – Cameron Castillo Jan 16 '18 at 06:55
  • try running it as admin – Royi Mindel Jan 16 '18 at 06:58
  • https://stackoverflow.com/questions/2818179/how-do-i-force-my-net-application-to-run-as-administrator/2818776#2818776 – Royi Mindel Jan 16 '18 at 06:58