Create scheduled task in Windows Task Scheduler - part 2
Published on: 9th Dec 2019
Updated on: 16th Jan 2022
Explanation
The following script demo shows how to create daily & weekly tasks.
$task_folder = "\myTasks\"
$ps_script_file = "d:\temp5\test-script.ps1"
<###########################################
this is task #3 - DAILY
###########################################>
$task_name = "myTask3"
## 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"""
$sch = New-ScheduledTaskTrigger -Daily -At 5pm
Register-ScheduledTask -TaskName $task_name -TaskPath $task_folder -Action $axn -Trigger $sch
Write-Host "created new task $task_name"
}
else {
Write-Host "$task_name task already exists"
}
<###########################################>
$task_name = "myTask3-1"
$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"""
$sch = New-ScheduledTaskTrigger -Daily -At 1am
$task = Register-ScheduledTask -TaskName $task_name -TaskPath $task_folder -Action $axn -Trigger $sch
# run every 30 minutes
$task.Triggers.Repetition.Interval = "PT30M"
# for 12 hours. For 1 days, use "P1D".
$task.Triggers.Repetition.Duration = "PT12H"
# update the task
$task | Set-ScheduledTask
Write-Host "created new task $task_name"
}
else {
Write-Host "$task_name task already exists"
}
<###########################################
this is task #4 - WEEKLY
###########################################>
$task_name = "myTask4"
$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"""
# runs at 6:30pm.
$sch = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday, Friday -At "18:30"
Register-ScheduledTask -TaskName $task_name -TaskPath $task_folder -Action $axn -Trigger $sch
Write-Host "created new task $task_name"
}
else {
Write-Host "$task_name task already exists"
}
Jump to #POWERSHELL blog
Author
Lau Hon Wan, software developer.