Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 367
Bert Avatar asked Dec 02 '17 19:12

Bert


People also ask

How do I schedule a PowerShell script to run daily?

Create a Trigger to Auto run the Scheduled PowerShell Script Then click New. The New Trigger window will open. On the Begin the task drop-down, ensure that On a schedule is selected. Then select whether you want to Schedule the PowerShell Script to run Daily, Weekly or Monthly.

How do I stop a scheduled task in PowerShell?

All you have to do is launch PowerShell with admin rights and type Disable-ScheduledTask -TaskName "<Task Name>". Then, press Enter. If the task isn't in the root folder, type Disable-ScheduledTask -TaskPath "\<task folder path>\" -Task Name "<Task Name>".


1 Answers

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)
like image 140
Jarrad Avatar answered Oct 14 '22 08:10

Jarrad