Creating a Windows Scheduled Task using PowerShell


I find myself creating Windows Scheduled Tasks very often to run a PowerShell Script on a scheduled basis, and while PowerShell V3 will provide Cmdlets to manage the Scheduling Engine – V2 does not. I typically just create the Scheduled Tasks manually, but that is becoming less desirable as I work on larger SharePoint engagements with multiple environments, each with lots of servers. After doing a little online research, I found a few posts which were pretty close – the one which got me 80% of the way was this great post, which ironically was created for the same reason as mine – warming up SharePoint.

I took the code from the post mentioned above and tweaked it for my purposes, and I ended up with a fairly reusable script which takes a few parameters and also uses Get-Credential to actually accept credentials without the need to type the password in plain-text.

The way this script is composed is to create a task on the current machine by default, but by providing the optional HostName parameter – the script can be run against remote machines. It also will schedule it to start running starting tomorrow at 5:00 AM – it will then run daily at 5:00 AM.

Here’s the script!

<#
.Synopsis
	This PowerShell Script is used to create a scheduled task on a specified machine.
.Description
	This PowerShell Script uses the Schedule.Service COM Object to create a Windows
    Scheduled Task on a specified machine. Using the parameters provided, you can 
    specify the name, hostname, program to launch and the location of the script or file you're
    opening. The person executing the script will have to provide credentials.
.Example
	C:\PS>.\Create-ScheduledTask.ps1 -Description 'SharePoint Warmup' -ScriptPath C:\Scripts\Start-SPWarmUp.ps1
	This example creates a scheduled task on the current machine to run a script at C:\Scripts\Start-SPWarmup.ps1
    daily at 5:00 AM. The script will run with highest privileges.
.Notes
	Name: .\Create-ScheduledTask.ps1
	Author: Ryan Dennis
	Last Edit: 7/02/2012
	Keywords: Create Scheduled Task
.Link
	http://www.sharepointryan.com, http://twitter.com/SharePointRyan
#>

[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][System.String]$Description,
[Parameter(Mandatory=$false)][System.String]$HostName=$ENV:ComputerName,
[Parameter(Mandatory=$false)][System.String]$Program="PowerShell.exe",
[Parameter(Mandatory=$true)][System.String]$ScriptPath
)

# Date Variables #
$date = (Get-Date 05:00AM).AddDays(1)
$taskStartTime = $date | Get-Date -Format yyyy-MM-ddTHH:ss:ms

# Get the credentials #
$creds = Get-Credential
$UserName = $creds.UserName
$Password = $creds.GetNetworkCredential().Password

# Build the Argument based on Prefix, Suffix and ScriptPath parameter #
$argPrefix = '-command "& {'
$argSuffix = '}"'
$programArguments = $argPrefix+$ScriptPath+$argSuffix

$service = New-Object -ComObject "Schedule.Service"
$service.Connect($Hostname)
$rootFolder = $service.GetFolder("\")
$taskDefinition = $service.NewTask(0)
$regInfo = $taskDefinition.RegistrationInfo
$regInfo.Description = $Description
$regInfo.Author = $UserName
$settings = $taskDefinition.Settings
$settings.Enabled = $True
$settings.StartWhenAvailable = $True
$settings.Hidden = $False
$triggers = $taskDefinition.Triggers
$trigger = $triggers.Create(2)
#$startTime = "2006-05-02T22:00:00"
$trigger.StartBoundary = $taskStartTime
$trigger.DaysInterval = 1
$trigger.Id = "DailyTriggerId"
$trigger.Enabled = $True
$Action = $taskDefinition.Actions.Create(0)
$Action.Path = $Program
$Action.Arguments = $programArguments
$Principal = $taskDefinition.Principal
# Principal.RunLevel -- 0 is least privilege, 1 is highest privilege #
$Principal.RunLevel = 1
$rootFolder.RegisterTaskDefinition($Description, $taskDefinition, 6, $UserName, $Password, 1)
Advertisements

2 thoughts on “Creating a Windows Scheduled Task using PowerShell

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s