I'm trying to create a Scheduled Task with the following Trigger:
- Run every 5 minutes
- Run indefinitely
In the GUI I can do this easily by selecting:
- Begin the task: at startup
And in the Advanced tab:
- Repeat task every: 5 minutes
- For a duration of: indefinitely
But I'm having trouble doing it with Powershell.
My troubled code:
$repeat = (New-TimeSpan -Minutes 5)
$duration = ([timeSpan]::maxvalue)
$trigger = New-ScheduledTaskTrigger -AtStartup -RepetitionInterval $repeat -RepetitionDuration $duration
It won't take the RepetitionInterval and RepetitionDuration parameters. But I need that functionality. How could I accomplish my goal?
To set the task literally with a "Startup" trigger and a repetition, it seems you have to reach in to COM (or use the TaskScheduler UI, obviously..).
# Create the task as normal $action = New-ScheduledTaskAction -Execute "myApp.exe" Register-ScheduledTask -Action $action -TaskName "My Task" -Description "Data import Task" -User $username -Password $password # Now add a special trigger to it with COM API. # Get the service and task $ts = New-Object -ComObject Schedule.Service $ts.Connect() $task = $ts.GetFolder("\").GetTask("My Task").Definition # Create the trigger $TRIGGER_TYPE_STARTUP=8 $startTrigger=$task.Triggers.Create($TRIGGER_TYPE_STARTUP) $startTrigger.Enabled=$true $startTrigger.Repetition.Interval="PT10M" # ten minutes $startTrigger.Repetition.StopAtDurationEnd=$false # on to infinity $startTrigger.Id="StartupTrigger" # Re-save the task in place. $TASK_CREATE_OR_UPDATE=6 $TASK_LOGIN_PASSWORD=1 $ts.GetFolder("\").RegisterTaskDefinition("My Task", $task, $TASK_CREATE_OR_UPDATE, $username, $password, $TASK_LOGIN_PASSWORD)
New-ScheduledTaskTrigger uses parameter sets. When you specify that you want the scheduled task to start up "at logon" you are restricting yourself to the following parameter set:
Parameter Set: AtStartup New-ScheduledTaskTrigger [-AtStartup] [-RandomDelay <TimeSpan> ] [ <CommonParameters>]
What may be more beneficial is if you use your "at startup" scheduled task to register a new scheduled task to run every five minutes using the "once" parameter set:
Parameter Set: Once New-ScheduledTaskTrigger [-Once] -At <DateTime> [-RandomDelay <TimeSpan> ] [-RepetitionDuration <TimeSpan> ] [-RepetitionInterval <TimeSpan> ] [ <CommonParameters>]
Your Scheduled Task Trigger should successfully be assigned once you are using the correct parameter set.
See my answer here: https://stackoverflow.com/a/61646465/2943191
It is actually relatively simple, once a working example is written, of course.