PowerShell: Create Windows Scheduled Task to run Powershell script every hour

If you are using a newer version of PowerShell, then by all means use the New-ScheduledTaskAction, New-ScheduledTaskTrigger, and Register-ScheduledTask and  to create a Windows schedule task using PS scripting.

But if you still need to be compatible back to PowerShell 2.0, and want to keep it simple, you can avoid using the Schedule.Service COM interface, and run schtasks.exe directly instead.

Calling a Powershell Script

From within a powershell script you can invoke the schtasks executable directly.  The command below schedules creates a task to run a PowerShell script at the top of the hour (:00), every hour, as SYSTEM.

$hour24 = (Get-Date).ToString("HH:00")
& schtasks /create /tn MyPSScheduledTask /sc HOURLY /mo 1 /ST ${hour24} /f /ru SYSTEM /tr "powershell executionpolicy -bypass c:\temp\MyScript.ps1 'param value 1' 'param value 2'"

This must be run from a console with elevated privileges or you get a permissions error.  There is a maximum length of 261 characters for the command and parameters (everything after /tr).

Because you can’t set the working directory using this method, you may want to change directory to the one the script is located in when it is invoked.  Powershell v3.0 has $PSScriptRoot, but for Powershell v2.0 use code like below.

$thisDir = split-path -parent $MyInvocation.MyCommand.Definition
cd $thisDir

Calling a Batch File

Creating a scheduled task for a target batch file looks very similar.

$hour24 = (Get-Date).ToString("HH:00")
& schtasks /create /tn MyBATScheduledTask /sc HOURLY /mo 1 /ST ${hour24} /f /ru SYSTEM /tr "c:\temp\mybatch.bat"

Because you can’t set the working directory using this method, I would suggest adding a line to the top of your .bat file so that it changes directory to the location of the .bat file when invoked.

cd /d %~dp0

 

REFERENCES

https://blogs.technet.microsoft.com/heyscriptingguy/2015/01/13/use-powershell-to-create-scheduled-tasks/ (example with PS 3.0)

https://gallery.technet.microsoft.com/scriptcenter/for-windows-7-and-less-1042e194 (example)

https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtask?view=win10-ps

https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasktrigger?view=win10-ps

https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask?view=win10-ps

https://blogs.technet.microsoft.com/heyscriptingguy/2015/07/06/powertip-use-powershell-to-display-time-in-24-hour-format/ (24 hour format for time)