Skip to content

Instantly share code, notes, and snippets.

@tophatsteve
Created November 2, 2012 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tophatsteve/4000068 to your computer and use it in GitHub Desktop.
Save tophatsteve/4000068 to your computer and use it in GitHub Desktop.
Add a scheduled task from an XML template file
#
# Customise the XML used to create a scheduled task, then create the task.
#
function Get-Script-Directory
{
$scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value
return Split-Path $scriptInvocation.MyCommand.Path
}
# task definition file is in same directory as script
$installDir = Get-Script-Directory
# customise task
$xmlFileName = $installDir + "\TaskDefinition.xml"
$xmlFile = gi $xmlFileName
$xml = [xml](Get-Content $xmlFile)
$exePath = '"' + $installDir + "\TaskExecutable.exe" + '"'
$xml.Task.RegistrationInfo.Author = $env:username
$xml.Task.RegistrationInfo.Date = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ss")
# set start time to next 12:00 or 00:00 boundary
$currentHour = [int](Get-Date -Format "HH")
if($currentHour -lt 12)
{
$xml.Task.Triggers.TimeTrigger.StartBoundary = (Get-Date).ToString("yyyy-MM-dd") + "T12:00:00"
}
else
{
$xml.Task.Triggers.TimeTrigger.StartBoundary = (Get-Date).AddDays(1).ToString("yyyy-MM-dd") + "T00:00:00"
}
$xml.Task.Actions.Exec.Command = $exePath
$xml.Task.Actions.Exec.WorkingDirectory = $installDir.ToString()
$xml.Save($xmlFile.FullName)
# add task
$schTaskExePath = $env:windir + "\System32\schtasks.exe"
$quotedXmlFileName = '"' + $xmlFileName + '"'
$schTaskCmd = "$schTaskExePath /Create /TN MyTaskName /XML $quotedXmlFileName"
$result = invoke-expression $schTaskCmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment