Friday, 24 September 2010

New-Task.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script creates a scheduled task object. 
  4. .DESCRIPTION 
  5.     This script re-implements an MSDN sample using PowerShell 
  6. .NOTES 
  7.     File Name  : New-Task.ps1 
  8.     Author     : Thomas Lee - tfl@psp.co.uk 
  9.     Requires   : PowerShell Version 2.0 
  10. .LINK 
  11.     This script posted to: 
  12.         http://www.pshscripts.blogspot.com 
  13.     MSDN sample posted tot: 
  14.         http://msdn.microsoft.com/en-us/library/aa383665%28VS.85%29.aspx 
  15. .EXAMPLE 
  16.     PSH [C:\foo]: .\New-Task.ps1
  17.     Time Now       : 9/24/2010 12:43:47 PM 
  18.     Task startTime : 2010-09-24T12:44:17 
  19.     Task endTime   : 2010-09-24T12:48:47 
  20.     Task definition created. About to submit the task... 
  21.   
  22.   
  23.     Name               : Test TimeTrigger 
  24.     Path               : Test TimeTrigger 
  25.     State              : 3 
  26.     Enabled            : True 
  27.     LastRunTime        : 12/30/1899 12:00:00 AM 
  28.     LastTaskResult     : 1 
  29.     NumberOfMissedRuns : 0 
  30.     NextRunTime        : 9/24/2010 12:44:17 PM 
  31.     Definition         : System.__ComObject 
  32.     Xml                : <?xml version="1.0" encoding="UTF-16"?> 
  33.                          <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"
  34.                            <RegistrationInfo> 
  35.                              <Author>Thomas Lee</Author> 
  36.                              <Description>Start notepad at a certain time</Description> 
  37.                            </RegistrationInfo> 
  38.                            <Triggers> 
  39.                              <TimeTrigger id="TimeTriggerId"
  40.                                <StartBoundary>2010-09-24T12:44:17</StartBoundary> 
  41.                                <EndBoundary>2010-09-24T12:48:47</EndBoundary> 
  42.                                <ExecutionTimeLimit>PT5M</ExecutionTimeLimit> 
  43.                                <Enabled>true</Enabled> 
  44.                              </TimeTrigger> 
  45.                            </Triggers> 
  46.                            <Settings> 
  47.                              <IdleSettings> 
  48.                                <Duration>PT10M</Duration> 
  49.                                <WaitTimeout>PT1H</WaitTimeout> 
  50.                                <StopOnIdleEnd>true</StopOnIdleEnd> 
  51.                                <RestartOnIdle>false</RestartOnIdle> 
  52.                              </IdleSettings> 
  53.                              <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> 
  54.                              <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> 
  55.                              <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> 
  56.                              <AllowHardTerminate>true</AllowHardTerminate> 
  57.                              <StartWhenAvailable>true</StartWhenAvailable> 
  58.                              <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> 
  59.                              <AllowStartOnDemand>true</AllowStartOnDemand> 
  60.                              <Enabled>true</Enabled> 
  61.                              <Hidden>false</Hidden> 
  62.                              <RunOnlyIfIdle>false</RunOnlyIfIdle> 
  63.                              <WakeToRun>false</WakeToRun> 
  64.                              <ExecutionTimeLimit>PT72H</ExecutionTimeLimit> 
  65.                              <Priority>7</Priority> 
  66.                            </Settings> 
  67.                            <Actions Context="Author"
  68.                              <Exec> 
  69.                                <Command>C:\Windows\System32\notepad.exe</Command> 
  70.                              </Exec> 
  71.                            </Actions> 
  72.                            <Principals> 
  73.                              <Principal id="Author"
  74.                                <UserId>COOKHAM\tfl</UserId> 
  75.                                <LogonType>InteractiveToken</LogonType> 
  76.                              </Principal> 
  77.                            </Principals> 
  78.                          </Task> 
  79.  
  80.     Task submitted. 
  81. #> 
  82. # Helper Function 
  83. function XMLTIME{ 
  84. Param ( $T) 
  85. $csecond = $t.Second.ToString() 
  86. $cminute = $t.minute.ToString() 
  87. $chour = $t.hour.ToString() 
  88. $cday  = $t.day.ToString() 
  89. $cmonth  = $t.month.ToString() 
  90. $cyear = $t.year.ToString() 
  91.  
  92. $date =  $cyear + "-" 
  93. if ($cmonth.Length -eq 1) { $date += "0" + $cmonth + "-"}  
  94. else                      { $date += $cmonth + "-"
  95. if ($cday.length -eq 1)   { $date += "0" + $cday + "T"
  96. else                      { $date += $cday + "T"
  97. if ($chour.length -eq 1)  { $date += "0" + $chour + ":"
  98. else                      { $date += $chour + ":"
  99. if ($cminute.length -eq 1){ $date += "0" + $cminute + ":"
  100. else                      { $date += $cminute + ":"
  101. if ($csecond.length -eq 1){ $date += "0" + $csecond} 
  102. else                      { $date += $csecond} 
  103. # return 
  104. $date 
  105.  
  106. ## Script starts here 
  107.  
  108. # A constant that specifies a time-based trigger. 
  109. $TriggerTypeTime = 1 
  110. # A constant that specifies an executable action. 
  111. $ActionTypeExec = 0    
  112.  
  113. # Create and connect to the service 
  114. $service = New-Object -com schedule.service  
  115. $service.Connect() 
  116.  
  117. # Get a folder to create a task definition in.  
  118. $rootFolder = $service.GetFolder("\") 
  119.  
  120. # The taskDefinition variable is the TaskDefinition object. 
  121. # The flags parameter is 0 because it is not supported. 
  122. $taskDefinition = $service.NewTask(0)  
  123.  
  124. # Define information about the task. 
  125. # Set the registration info for the task by  
  126. # creating the RegistrationInfo object. 
  127. $regInfo = $taskDefinition.RegistrationInfo 
  128. $regInfo.Description = "Start notepad at a certain time" 
  129. $regInfo.Author = "Thomas Lee" 
  130.  
  131. # Set the principal for the task 
  132. $principal = $taskDefinition.Principal 
  133.  
  134. # Set the logon type to interactive logon 
  135. $principal.LogonType = 3 
  136.  
  137. # Set the task setting info for the Task Scheduler by 
  138. # creating a TaskSettings object. 
  139. $settings = $taskDefinition.Settings 
  140. $settings.Enabled = $True 
  141. $settings.StartWhenAvailable = $True 
  142. $settings.Hidden = $False 
  143.  
  144. # Create a time-based trigger. 
  145. $triggers = $taskDefinition.Triggers 
  146. $trigger = $triggers.Create($TriggerTypeTime) 
  147.  
  148. # Trigger variables that define when the trigger is active. 
  149. $time = ([system.datetime]::now).addseconds(30) 
  150. $startTime = XmlTime($time) 
  151.  
  152. $time = ([system.datetime]::now).addminutes(5) 
  153. $endTime = XmlTime($time) 
  154.  
  155. "Time Now       : {0}" -f (Get-Date -display time) 
  156. "Task startTime : {0}" -f $startTime 
  157. "Task endTime   : {0}" -f $endTime 
  158.  
  159. $trigger.StartBoundary = $startTime 
  160. $trigger.EndBoundary = $endTime 
  161. $trigger.ExecutionTimeLimit = "PT5M"    #Five minutes 
  162. $trigger.Id = "TimeTriggerId" 
  163. $trigger.Enabled = $True 
  164.  
  165. # Create the action for the task to execute. 
  166.  
  167. # Add an action to the task to run notepad.exe. 
  168. $Action = $taskDefinition.Actions.Create( $ActionTypeExec ) 
  169. $Action.Path = "C:\Windows\System32\notepad.exe" 
  170.  
  171. "Task definition created. About to submit the task..." 
  172.  
  173. # Register (create) the task. 
  174. $rootFolder.RegisterTaskDefinition("Test TimeTrigger", $taskDefinition, 6,"" ,"" , 3) 
  175.  
  176. # all done! 
  177. "Task submitted." 

2 comments:

David said...

Why not use schtasks.exe that they give you, you can create a task with one line. You can then make it run as System with one more line. Then you can execute the task with one more line.

Much easier

Thomas said...

David,

Thanks for the comment. The purpose of this blog, and this sample, is to show how you can use PowerShell and the underlying components can be used. In this case, I was using the COM object schedule.service to re-implement an MSDN sample.

As with everything PowerShell, there are always multiple ways to do almost anything!

Thanks for the comment.