How to create a Scheduled task with a task scheduler using PowerShell?


To create a task using GUI (As shown below image) we need a few settings like the Name of the task, trigger, and Action.

Similarly, to create a new task in task scheduler using PowerShell comprises of several settings.

  • Name of the task
  • The time when the task to trigger
  • Action − Do we need to schedule a program for execution or send an email on some event trigger.
  • Description − This is optional. You can add a description of the task.
  • Registering task − Final step is to register the created task.

Above all actions use different cmdlets but they are part of a ScheduledTasks module. To schedule task on local or remote servers, you need to ensure the module should be present on the server.

Get-Module ScheduledTasks | Select -ExpandProperty ExportedCommands

Let's begin creating a task.

  • Creating a new Task Action.
$tsaction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument 'C:\Temp\TestTask.ps1'
  • Mention the user account to run the script (optional).
$User= "NT AUTHORITY\SYSTEM"
  • Creating a time to trigger a task.
$tstrigger = New-ScheduledTaskTrigger -At 4:00PM -Once

You can provide the various timing for a routine task like Daily, monthly, or other as shown in the below example. In this example, we need to run a task once at 4:00 PM.

  • Register Schedule task.

Once the required settings are configured for a task, we need to register the task at the final step to appear in the task scheduler using the below command line.

               

Register-ScheduledTask `
  -TaskName 'Test Task' `
  -User $User `
  -Action $tsaction `
  -Trigger $tstrigger `
  -RunLevel Highest -Force

Final Script:

$tsaction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument 'C:\Temp\TestTask.ps1'$User= "NT AUTHORITY\SYSTEM"

$tstrigger = New-ScheduledTaskTrigger -At 4:00PM -Once

Output

Register-ScheduledTask `
 -TaskName 'Test Task' `

  -User $User `

   -Action $tsaction `

  -Trigger $tstrigger `

   -RunLevel Highest -Force

Once you run the above command, task will be created. Output will be as shown in the console.

You can check the same in the task scheduler.

Updated on: 28-Dec-2020

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements