Posted on October 26, 2017 · Posted in Powershell, Windows Server 2008 R2, Windows Server 2012 R2

How to Create Scheduled Task Using PowerShell

Most administrators use the graphic interface of Taskschd.msc console to create Windows Task Scheduler jobs. However, in various scripts and automated jobs, it is much more convenient to use the PowerShell features to create scheduled tasks. In this article, we’ll show how to create new Windows Scheduler tasks, export tasks into XML files and import them to other computers using PowerShell (v2.0 and 4.0).

Suppose, we need to create a scheduled task that would run during startup (or at a certain time) and execute some PowerShell script or command.

How to Create a Scheduled Task in PowerShell 2.0

In Powershell 2.0 (Windows 7, Windows Server 2008 R2), to create a repeated task (ScheduledJob) in PowerShell you can use Schedule.Service COM interface. In this example, we create a scheduled task that will execute the specific file containing PowerShell script during startup. The task is performed with the system privileges.

$TaskName = "NewPsTask"
$TaskDescription = "Running PowerShell script from Task Scheduler"
$TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
$TaskScript = "C:\PS\StartupScript.ps1"
$TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted -file $TaskScript"
$TaskStartTime = [datetime]::Now.AddMinutes(1)
$service = new-object -ComObject("Schedule.Service")
$service.Connect()
$rootFolder = $service.GetFolder("\")
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = "$TaskDescription"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$triggers = $TaskDefinition.Triggers
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx
$trigger = $triggers.Create(8)

Note. In this case, a trigger is created that is activated during the boot (code 8). See the full list of codes below:

TASK_TRIGGER_EVENT 0
TASK_TRIGGER_TIME 1
TASK_TRIGGER_DAILY 2
TASK_TRIGGER_WEEKLY 3
TASK_TRIGGER_MONTHLY 4
TASK_TRIGGER_MONTHLYDOW 5
TASK_TRIGGER_IDLE 6
TASK_TRIGGER_REGISTRATION 7
TASK_TRIGGER_BOOT 8
TASK_TRIGGER_LOGON 9
TASK_TRIGGER_SESSION_STATE_CHANGE 11

$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.Enabled = $true
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand"
$action.Arguments = "$TaskArg"
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx
$rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5)

After executing the command, a new task NewPsTask appears in Task Scheduler.

new task in task scheduler

The syntax of the commands is quite complicated, so the developers have added a separate TaskScheduler module to PowerShell Pack (a part of Windows 7 Resource Kit) that significantly simplifies the creation of scheduled tasks in PowerShell 2.0. After the module is installed, you can create a task using the following commands:

Import-Module TaskScheduler $task = New-Task
$task.Settings.Hidden = $true
Add-TaskAction -Task $task -Path C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe –Arguments “-File C:\MyScript.ps1”
Add-TaskTrigger -Task $task -Daily -At “10:00”
Register-ScheduledJob –Name ”ShTaskPs” -Task $task

How to Create a Scheduled Task in PowerShell 4.0 (Windows Server 2012 R2)

In PowerShell 3.0 and 4.0 used in Windows Server 2012 R2 and Windows 8.1 new cmdlets to create scheduled tasks appeared: New-ScheduledTaskTrigger, Register-ScheduledTask. Now creating scheduled tasks has become easier and more convenient.

Create a task with the name StartupScript_PS, which runs a PoSh script located in C:\PS\StartupScript.ps1 under SYSTEM account at 10 AM every day. The task will be performed with elevated privileges (checkbox “Run with highest privileges”).

$Trigger= New-ScheduledTaskTrigger -At 10:00am -Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\PS\StartupScript.ps1"
Register-ScheduledTask -TaskName "StartupScript_PS" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force

Tip. If you want the task to run every time during startup, the first command has to be as follows:
$Trigger= New-ScheduledTaskTrigger -AtStartup
If you want it to run when a user logs on:
$Trigger= New-ScheduledTaskTrigger -AtLogon

New-ScheduledTaskTrigger

Let’s make sure that a new task has appeared in Task Scheduler..

task properties

How to Export a Scheduled Task into XML File

PowerShell allows to export the current settings of any scheduler task into a text XML file. So you can export the parameters of any task and distribute a task of any complexity level to other computers on the network. The task may be exported both in Task Scheduler graphic interface and in PowerShell command prompt.

Here is the command to export the task with the name StartupScript_PS into the file named StartupScript_PS.xml:

Export-ScheduledTask "StartupScript_PS" | out-file c:\tmp\StartupScript_PS.xml

task settings xml file

Export-ScheduledTask cmdlet won’t work in PowerShell 2.0, so in Windows 7 / 2008 R2 it’s better to use the integrated tool schtasks to export the task settings and redirect the result into a text file:

schtasks /query /tn "NewPsTask" /xml >> "c:\tmp\NewPsTask.xml"

Tip. We remind that earlier the built-in console utilit schtasks.exe was used to create and manage scheduled tasks.

How to Import a Scheduled Task from XML File

After the scheduled task settings are exported to the XML file, it can be imported to any network computer using the graphic console, SchTasks.exe or PowerShell.

Register-ScheduledTask cmdlet will help you to import the task settings and register it.
Register-ScheduledTask -Xml (Get-Content “\\Srv1\public\NewPsTask.xml” | out-string) -TaskName "NewPsTask"

Register-ScheduledTask

In PowerShell 2.0 (Windows 7/Server 2008 R2), it is easier to import a task using schtasks. The first command creates a new task. The second will run it right away (without waiting for the trigger to activate it).

schtasks /create /tn "NewPsTask" /xml "\\Srv1\public\NewPsTask.xml" /ru corp\skrutapal /rp Pa$$w0rd
schtasks /Run /TN "NewPsTask"

Note. Please, note that this example uses the credentials of the account that is used to run the task. If the credentials are not specified, because they are not stored in the job, they will be requested when importing.

Previous:
Next:
Related Articles