Tuesday, February 22, 2011

Scheduling Tasks in PowerShell for Windows Server 2008 -- Part 2: Weekly Tasks

In my previous blog post, "Scheduling Tasks in PowerShell for Windows Server 2008 -- Part 1: Monthly Task", I laid the groundwork for the various ways you can schedule tasks in Windows Server 2008. This installment of the series shows how to create a weekly task with multiple triggers. In the code sample below, I schedule a report to run on Monday (2), Wednesday (8) and Thursday (16) at 4:30 pm local time to the server. To extend this example further, you could use a hash table to establish a different time of day for each of the day of the week task triggers.
# Parameters to modify
$taskName = "Export-TriWeeklyDataDeobfuscationReport.ps1"
$taskWorkingDirectory = "C:\PowerShell"
$taskAuthor = "ad\myaccount"
$taskDescription = "The Tri-Weekly Data Deobfuscation Report"
$taskSecurityPrincipal = "ad\myaccount"
$taskShedulerTaskFolder = "\MyTasks"
$startTime = (Get-Date "02/28/2011 16:30:00" -Format s)
$daysOfWeek = @("2","8","16") # http://msdn.microsoft.com/en-us/library/aa381905(v=VS.85).aspx

# Would like to use -asSecureString but RegisterTaskDefinition does not accept it
# Look over your shoulder before typing
$password = Read-Host -prompt "$taskSecurityPrincipal Password"

# The meaty parts

$taskService = New-Object -ComObject Schedule.Service
$taskService.Connect()

$rootFolder = $taskService.GetFolder($taskShedulerTaskFolder)

$taskDefinition = $taskService.NewTask(0)

$registrationInformation = $taskDefinition.RegistrationInfo
$registrationInformation.Description = $taskDescription
$registrationInformation.Author = $taskAuthor

$taskPrincipal = $taskDefinition.Principal
$taskPrincipal.LogonType = 1
$taskPrincipal.UserID = $taskSecurityPrincipal
$taskPrincipal.RunLevel = 0

$taskSettings = $taskDefinition.Settings
$taskSettings.StartWhenAvailable = $true
$taskSettings.RunOnlyIfNetworkAvailable = $true
$taskSettings.Priority = 7
$taskSettings.ExecutionTimeLimit = "PT2H"

$taskTriggers = $taskDefinition.Triggers

foreach($dayOfWeek in $daysOfWeek) {
 $executionTrigger = $taskTriggers.Create(3) 
 $executionTrigger.DaysOfWeek = $dayOfWeek
 $executionTrigger.StartBoundary = $startTime
}

$taskAction = $taskDefinition.Actions.Create(0)
$taskAction.Path = "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe"
$taskAction.Arguments = "-command `"$taskWorkingDirectory\$taskName`""
$taskAction.WorkingDirectory = $taskWorkingDirectory

# 6 == Task Create or Update
# 1 == Password must be supplied at registration
$rootFolder.RegisterTaskDefinition($taskName, $taskDefinition, 6, $taskSecurityPrincipal, $password, 1)

# Since we captured this in plain text I am going to nuke the value
# Not 100% security. Close the PowerShell command window.
Clear-Variable -name password

No comments:

Post a Comment