Multiple triggers on a scheduled task

Datetime:2016-08-23 02:55:36          Topic: ActionScript  PowerShell           Share

Setting up a scheduled task can be accomplished like this:

$taskname = ‘Test Job’

Get-ScheduledTask -TaskName $taskname -ErrorAction SilentlyContinue |  Unregister-ScheduledTask -Confirm:$false

$trigger = New-ScheduledTaskTrigger -Daily -At 03:00

$actionscript = ‘-NoExit -NonInteractive -NoProfile -WindowStyle Normal -NoLogo -Command “&{get-process}”‘

$pstart =  “C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe”

$action = New-ScheduledTaskAction -Execute $pstart -Argument $actionscript Register-ScheduledTask -TaskName $taskname -Action $action -Trigger $trigger -RunLevel Highest -Description “Test job”

Define the task name and then unregister (remove) any instances of that task

You then define the trigger and actions and finally register the task with the name you defined earlier.

The script above will create a task to run at 3am.

You can force the task to run as a test:

Start-ScheduledTask -TaskName ‘Test Job’

But what about if you want to run the task multiple times during the day. Simple.  You define multiple triggers:

$taskname = ‘Test Job’

Get-ScheduledTask -TaskName $taskname -ErrorAction SilentlyContinue |  Unregister-ScheduledTask -Confirm:$false

$triggers = @()

$triggers += New-ScheduledTaskTrigger -Daily -At 03:00

$triggers += New-ScheduledTaskTrigger -Daily -At 09:00

$triggers += New-ScheduledTaskTrigger -Daily -At 15:00

$triggers += New-ScheduledTaskTrigger -Daily -At 21:00

$actionscript = ‘-NoExit -NonInteractive -NoProfile -WindowStyle Normal -NoLogo -Command “&{get-process}”‘

$pstart =  “C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe”

$action = New-ScheduledTaskAction -Execute $pstart -Argument $actionscript Register-ScheduledTask -TaskName $taskname -Action $action -Trigger $triggers -RunLevel Highest -Description “Test job”

Define an array and then add the triggers into it. Remember to use the array when you register the task.

You can test the triggers on a scheduled task:

Get-ScheduledTask -TaskName ‘Test Job’ | select -ExpandProperty Triggers





About List