Scheduled task creation using Powershell

Let’s talk today a little bit about how to create scheduled task using Powershell.
Windows admins who created big number of task scheduler jobs know that is not very fascinating job.
There is a lot of clicking and it’s really boring. So let’s automate it!.

First of all you should define $action scriptblock in which your custom script should be pasted and name of the task.

$action = { # Your script should be added here }
$name = "Every minute cleanup job"

In next step job trigger will be created which will define how often and when job should start.
For this purpose New-JobTrigger command should be used with proper switches.

$trigger = New-JobTrigger -Daily -at (Get-Date).AddMinutes(2)

Once it is done Register-ScheduledJob will be run which will create scheduled task.

Register-ScheduledJob -Name $name -Trigger $trigger -ScriptBlock $action 

Once the task is created we can proceed with adjusting scheduled task triggers (to be sure that it was created sleep script for 5 seconds)
In below example I’ve created task which is run every 1 minute each day.
To adjust trigger for your needs check ISO_8601 definition.

Start-Sleep 5
$task = Get-ScheduledTask -TaskName $Name
# P1D Set duration of one day
$task.Triggers.repetition.Duration = 'P1D'
# PT1M set interval to every minute
$task.Triggers.repetition.Interval = 'PT1M'
$task | Set-ScheduledTask

I hope that it will be usefull for some of you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.