Search code examples
windowspowershellpowershell-cmdletwindows-task-scheduler

How to create a task on windows using powershell and specified trigger


I'm trying to create a task on windows taskscreduler using the powershell but without success. The script I need to create based GUI description:

"At 08:00 every day -After triggered, repeat every 02:00:00 for a duration of 12 hours"

I already found the solution using multiple trigger that could work in this situation:

-Trigger @(New-ScheduledTaskTrigger -Daily -At 8am; New-ScheduledTaskTrigger -Daily -At 10am; New-ScheduledTaskTrigger -Daily -At 12pm; New-ScheduledTaskTrigger -Daily -At 2pm; New-ScheduledTaskTrigger -Daily -At 4pm; New-ScheduledTaskTrigger -Daily -At 6pm; New-ScheduledTaskTrigger -Daily -At 8pm)

But the problem is obvious....in the future if I need a task that run more times a day this script will become a monster. So, someone knows a better solution for that?


Solution

  • Given that New-ScheduledTaskTrigger doesn't allow you to combine -RepetitionInterval and -RepetitionDuration with -Daily, as you've discovered, you can use multiple triggers, which you can create algorithmically:

    Register-ScheduledTask ... `
      -Trigger (0..6).ForEach({ New-ScheduledTaskTrigger -Daily -At "$(8+2*$_):00" })
    

    Note:

    • These multiple triggers are also reflected in the Task Scheduler GUI (taskschd.msc) as such:

      • Task Scheduler screenshot
    • The underlying APIs are capable of representing this logic in a single trigger, as the description in your question ("At 08:00 every day -After triggered, repeat every 02:00:00 for a duration of 12 hours") demonstrates.

    • It is therefore unfortunate, that a purely syntactic restriction in New-ScheduledTaskTrigger limits access to some task-scheduler API features.

      • This related post offers workarounds that do allow use of a single trigger, but these workarounds are more verbose and therefore impractical for inline solutions.