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.
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.
$tsaction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument 'C:\Temp\TestTask.ps1'
$User= "NT AUTHORITY\SYSTEM"
$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.
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
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.