Creating Scheduled Tasks with PowerShell

Creating scheduled tasks on servers is something I do on a regular basis when building new Skype for Business environments, and it’s always a pain to create them via the GUI.

To speed things up, I have the scheduled tasks I need to run declared as scripts which will automatically create the scheduled tasks for me whenever I spin up a new environment.

These are made possible by the ScheduledTasks module, which was introduced with PowerShell v4, which allows you to define New-ScheduledTaskAction objects, which are triggered by New-ScheduledTaskTrigger objects as part of a New-ScheduledTask, which is then Registered with Register-ScheduledTask.

For example:

First, define the action which the task will perform. In this case, I’m going to launch a non-interactive instance of PowerShell and fire a script.
$Action = New-ScheduledTaskAction -Execute 'C:Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument "-NonInteractive -NoLogo -NoProfile -File 'C:\scripts\do-something.ps1'"

Second, how should this be triggered? There are quite a few options here, such as hourly, daily, weekly, etc. A complicated example which runs every two weeks on a sunday at 3am:
$Trigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 2 -DaysOfWeek Sunday -at 3am
For more options on this cmdlet, check either get-help new-scheduledtasktrigger or technet

Third, combine the action and trigger to make a task
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings (New-ScheduledTaskSettingsSet)

Finally, register the task and it’ll run the next time the trigger is fired
$Task | Register-ScheduledTask -TaskName "do-something every 2 weeks" -User 'administrator' -Password 'password in cleartext'

Further reading here:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s