1

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?

  • 1
    `New-ScheduledTaskTrigger -Daily -RepetitionInterval (New-TimeSpan -Hours 2) -RepetitionDuration (New-TimeSpan -Hours 12) -At 8:00` Could also try using the Repetition interval/duration parameters. – Grok42 May 09 '23 at 11:51
  • Does this answer your question? [Powershell: Scheduled Task with Daily Trigger and Repetition Interval](https://stackoverflow.com/questions/20108886/powershell-scheduled-task-with-daily-trigger-and-repetition-interval) – Patrick Mcvay May 09 '23 at 14:37
  • @Grok42 Don't work, you can't use "-Daily" and "-RepetitionInterval" together. That's the sintax https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasktrigger?view=windowsserver2022-ps – Patrick Geovani May 09 '23 at 17:01
  • @PatrickMcvay the solution selected to that another question don't seems to be a "good solution" as well, I was hoping that after some time someone had a inline solution, more like the Grok42 answer (but sadly dosn't work that way) – Patrick Geovani May 09 '23 at 17:06

1 Answers1

2

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.
mklement0
  • 382,024
  • 64
  • 607
  • 775