Today, I would like to discuss the topic of creating new tasks in the Windows Task Scheduler, which involves scheduling the execution of specific scripts or programs at a designated time or under certain conditions. In this article, I will demonstrate how to create new tasks in the scheduler using PowerShell, covering both basic and advanced versions. I will also show how to set key task parameters such as trigger, action.
A basic task in the Windows Task Scheduler has only one trigger and one action. The trigger is a condition that initiates the task, such as a specific date and time, a system event, or a user logon. The action is the task’s operation, such as running a PowerShell script, a program, or a document.
To create a task in the Windows Task Scheduler using PowerShell, we can utilize the New-ScheduledTask cmdlet. This cmdlet takes ScheduledTaskTrigger and ScheduledTaskAction objects as parameters, representing the task’s trigger and action, respectively. For example, to create a task that runs a PowerShell script named Test.ps1 every day at 10:00 AM, the following code can be used:
1 2 3 4 5 6 7 8 9 10 11 |
# Create trigger object $Trigger = New-ScheduledTaskTrigger -Daily -At 10am # Create action object $Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\Test.ps1" # Create task object $Task = New-ScheduledTask -Trigger $Trigger -Action $Action -Description "Start script at 10am" # Register scheduled task in scheduler Register-ScheduledTask -TaskName "Test" -InputObject $Task |
If we want to create a more advanced task, then depending on what we want to achieve, we need to add, for example, additional action options or triggers.
1 2 3 4 5 6 |
$Action1 = New-ScheduledTaskAction -Execute 'notepad' $Action2 = New-ScheduledTaskAction -Execute 'calc' $Trigger1 = New-ScheduledTaskTrigger -At 9am -Daily $Trigger2 = New-ScheduledTaskTrigger -AtLogon $options = New-ScheduledJobOption -StartIfOnBattery Register-ScheduledTask -Action $Action1, $Action2 -Trigger $Trigger1, $Trigger2 -TaskName "MyAdvancedTask" -Description "Runs notepad at 9am daily and calculator at logon" -ScheduledJobOption $options |
You can also create a task that launches a program or script upon user logon by utilizing the -AtLogon
parameter.
1 2 3 |
$Action = New-ScheduledTaskAction -Execute 'notepad' $Trigger = New-ScheduledTaskTrigger -AtLogon Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "MyTask" -Description "Start notepad at logon" |
To remove a task from the scheduler, simply execute the command:
1 |
Unregister-ScheduledTask -TaskName 'TaskName' -Confirm:$false |