Powersell - create scheduled task in Windows Task Scheduler - part 1

Published on: 2nd Dec 2019

Updated on: 23th Jul 2025

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.

In a nutshell, a task has the following components:

For illustration purpose, the following script creates an on demand task. This means, it 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

Advantages on using Powershell to schedule a task

Disadvantages on using Powershell to schedule a task

Conclusion

Powershell is helpful, convenient and fast in scheduling many tasks in one go because adding task through the GUI is time consuming. In case that you are managing more than one server, Powershell is the best way to create schedule task because the task will be created with the same setting (i.e., this enforce the "standardization of settings" which leads to easier server management).

Related posts

  1. Create scheduled task in Windows Task Scheduler - part 1
  2. Create scheduled task in Windows Task Scheduler - part 2
  3. Create scheduled task in Windows Task Scheduler - part 3

Back to #POWERSHELL blog

Back to #blog listing

Author

Lau Hon Wan, software developer.