powershellscheduled-tasks

Powershell Scheduled Task At Startup Repeating


I'm trying to create a Scheduled Task with the following Trigger:
- Startup
- 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?


Solution

  • 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)