Create scheduled task in Windows Task Scheduler
Published on: 2nd Dec 2019
Updated on: 16th Jan 2022
Explanation
Windows Task Scheduler is a utility that helps to execute any process periodically. For example, you want to sync your working files on a daily basis, scan a virus, process some data, etc.
A task has the following components:
- Action or multiple actions - which is the process that you want to run periodically. We use
New-ScheduledTaskAction
to create a new action object. - Trigger - which is the time to run the process and it can have multiple timing. We use
New-ScheduledTaskTrigger
to create a new trigger. - Security context - any process must run in a valid security context. We can set the context using
New-ScheduledTaskPrincipal
.
The following script creates an on demand task which requires the user to manually trigger the task.
$task_folder = "\myTasks\"
$task_name = "myTask2"
# this can be any Powershell script.
$ps_script_file = "d:\temp5\test-script.ps1"
## The first line will show err if $task_folder does not exist.
## The second line will not show any error if $task_folder does not exist.
#$exist = Get-ScheduledTask -TaskPath $task_folder | Where-Object {$_.TaskName -eq $task_name}
$exist = Get-ScheduledTask | where {$_.TaskPath -eq "\myTasks\" -and $_.TaskName -eq $task_name }
if (!$exist) {
$axn = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass ""$ps_script_file"""
Register-ScheduledTask -TaskName $task_name -TaskPath $task_folder -Action $axn
Write-Host "created new task"
}
else {
Write-Host "The task already exists"
}
The contents of test-script.ps1
$dt = (get-date).ToString()
Set-Content -Path "d:\temp5\test-ps-output.txt" -Value $dt
Jump to #POWERSHELL blog
Author
Lau Hon Wan, software developer.