Created
November 2, 2012 10:34
-
-
Save tophatsteve/4000068 to your computer and use it in GitHub Desktop.
Add a scheduled task from an XML template file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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