Create a Scheduled Task in PowerShell

Create a Scheduled Task in PowerShell

Creating a windows scheduled task from PowerShell is both harder than I expected and easier and is a good example of a multi-step cmdlet process coming together to build something that can have a lot of complication to it when viewed from the UI.

First we need to make sure the task does not already exist with Get-ScheduledTask. If it has not already been created, we need to work in three stages. We need:

  1. An action to perform, in this case run powershell.exe with our own .ps1 file as the argument.
  2. A trigger, say run the action daily at a given time.
  3. Registration of the task, bringing together the trigger, the action and a name and description.

[string]$TaskName = 'MyScheduledTask'
[string]$TaskDescription = 'Runs a powershell script every day'

$Task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue

If ($null -eq $Task) {

	[string]$here = Split-Path -Path $MyInvocation.MyCommand.Path
	[string]$ScriptPath = Join-Path -Path $here -ChildPath MyScheduledTask.ps1 
    [string]$ArgumentList = '-NoProfile -Command "' + $ScriptPath + '" '
    
	$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument $ArgumentList
    $Trigger = New-ScheduledTaskTrigger -Daily -At 2am
    
	Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName $TaskName -Description $TaskDescription | Out-Null
}