;; KixGenerated: 2013/11/23 08:01:38 / Kix32 Version 4.62 
;KGEN:NOPARSE 
;HEADER:Lib-TC:3.0:Glenn Barnas:A collection of Task Scheduler control functions 
; 
;LIBRARY        Lib-TC - Scheduled Tasks Control Function Library 
; 
;ACTION         A collection of Task Scheduler control functions 
; 
;AUTHOR         Glenn A. Barnas / Inno-Tech Consulting Group 
; 
;VERSION         3.0  -  2012/07/15 
;; 
;;HISTORY        1.0  -  2004/01/12 - Initial release 
;;               1.02 -  2004/02/05 - minor correction to better support AtStartup trigger 
;;			              Modified to return error message on failure instead of printing errors 
;;		 1.1  -  2007/12/21 - Changed method of executing JT.EXE to return failure codes 
;;		 1.2  -  2009/04/30 - Changed exec method to use KixForms first, then WSH to 
;;			              prevent CMD window displays when using KF apps. 
;;			              Added tcLibVer function to identify the library version string. 
;;		 2.0  -  2009/11/25 - Update to coding standards, positive logic 
;;               3.0  -  2012/07/15 - Full rewrite to use Schtasks instead of JT 
;;                                    Fully backward compatible from the Kix Library interface 
;; 
;;OVERVIEW       An integrated library of Windows Task Scheduler control functions 
;; 
;;REQUIRES       V3 and later:	SCHTASKS v1.1 (Windows Vista or Higher) 
;;		V2 and earlier:	JT.EXE - Microsoft Win-2K Resource Kit Tool 
;;                (Available from ftp://ftp.microsoft.com/reskit/win2000/jt.zip) 
;; 
;;SUMMARY        TASK    = 'what to run' - program & parameters, security 
;;               TRIGGER = 'when to run it' - one or more per task 
;;               EVENT   = 'task and related triggers' 
;; 
;;	tcLibVer()		Returns the current tcLib version string 
;;				  $Ver = tcLibVer() 
;;      tcInit()                Defines/Initialize a pair of Event arrays to defaults/nulls 
;;				  tcInit() 
;;      tcDefineTask()          Load a Task array with user data 
;;				  tcDefineTask(Task_params) 
;;      tcDefineTrigger()       Load a Trigger array with user data 
;;				  tcDefineTrigger(TrigID, Trigger_params) 
;;      tcGetEvent()            Loads arrays with specific task & trigger info 
;;				  $R = tcGetEvent(Host, EventName) 
;;      tcSetEvent()            Create / modify a scheduled event from task & trigger array data 
;;				  $R = tcSetEvent(Host, EventName) 
;;      tcDelEvent()            Delete an entire event (Task & all Triggers) 
;;				  $R = tcDelEvent(Host, EventName) 
;;      tcDelTrigger()          Delete a specific trigger 
;;				  $R = tcDelTrigger(Host, EventName, TrigID) 
;;      tcGetTasks()            Returns an array with list of task names from target 
;;				  $A = tcGetTasks(Host) 
;;      tcIsTask()              Determines if a specific task exists 
;;				  $R = tcIsTask(Host, EventName) 
;;      tcIsTrigger()           Determines if a specific trigger exists 
;;				  $R = tcIsTrigger(Host, EventName, TrigID) 
;;	tcExecute()		Executes the named task on the target 
;;				  $R = tcExecute(Host, EventName) 
;;	tcTerminate()		Terminates the named task on the target, if running 
;;				  $R = tcTerminate(Host, EventName) 
;;	tcSetEventCredentials()	Updates the named task's credentials 
;;				  $R = tcSetEventCredentials(Host, EventName, UserID, Passwd) 
;; 
;;               Supporting Functions - used internally only 
;;      tcSplitParms()          Returns an array of MNM=val pairs from a single string 
;;	tcExec()		Runs the JT command and returns the results 
;;	tcConvert()		Converts to/from cTime, returns date string in tcLib-required format 
;;	tcTextToBool()		Converts True/False text string to Boolean 1/0 
;;	tcBoolToText()		Converts Boolean 1/0 to True/False text string 
;;	tcDTFormat()		Convert DATE TIME string to dateTtime format 
;;	tcTimeFormat()		Converts a time value to PT#S seconds format 
;;	tcTimeVal()		Converts SCHTASKS time formats to tcLib format 
 
; 
;====================================================================== 
; Define UDF variables and constants 
; 
 
; return the tcLib version 
Function tcLibVer()
  $tcLibVer = $tcVERSION
  Exit 0
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcInit([Flag]) 
; 
;ACTION         Initializes the Task and Trigger arrays 
; 
;SYNTAX         tcInit([Flag]) 
; 
;PARAMETERS     Flag (optional) - if set, loads array with nulls instead of defaults 
;                                 This is recommended prior to the tcGetEvent function 
; 
;REMARKS        REVIEW THIS UDF FOR USER-DEFINED / ENVIRONMENT-SPECIFIC DEFINITIONS!!!!!!!!!!! 
; 
;		This function creates two arrays - $a_tcTask and $a_tcTrig - if not  
;               already defined. It then initializes the arrays with default data 
;               needed to create a task if no argument is passed, or with nulls (as 
;               needed to read task data from the target) when an argument of 1 is  
;		passed. If the argument is 2, it returns an array of 11 elements with 
;		default trigger data. This allows an existing task to request default 
;		trigger data when adding a new trigger. 
; 
;               $a_tcTask contains 27 elements - 0-19 are Task data, 20 & 21 are 
;               the User ID and Password, and 22-26 are 'read only' status info. 
; 
;               $a_tcTrig is a 11x10 element array, representing the 10 triggers permitted 
;               by this library. Each trigger array contains the 10 trigger parameters, 
;               plus an 11th element to track which triggers have been defined.  
; 
;               Any parameter requiring user definition will contain 'RQ', indicating 
;               that it was not yet initialized by the user. Parameters 0-19 are passed 
;               to the command to define the task. Parameters 20 & 21 will hold the credentials. 
;               Parameters 18 & 19 (Interactive & HaltOnError) are initialized 
;               but not yet used by jt.exe. 
; 
;               The default values - WorkingDirectory, Comment, and MaxRunTime - 
;               are all possible points of customization. 
; 
;RETURNS        Flag is null, 0, or 1 - Nothing - loads global arrays 
;		Flag is 2 - no init is done, returns single trigger array  
; 
;DEPENDENCIES   None 
; 
;EXAMPLES       tcInit() 
;                       Loads $a_tcTask and $a_tcTrig with default elements 
 
Function tcInit(OPTIONAL $_tcFlag)
 
  Dim $_aDefaults					; default event data 
  Dim $_Idx						; Trigger index pointer 
  Dim $_Date						; Default trigger date 
  Dim $_D						; temporary date value 
  Dim $_Time						; Default trigger time 
 
  ; Define global array & user-defined vars if not declared 
  If Not IsDeclared($tcEXE)
 
    Global $tcOUTPUT					; command output 
    Global $tcEXE					; path to command 
    Global $tcMAXTRIGGERS				; Max # of Triggers 
    Global $tcVERSION					; library version string 
    Global $tcWORKDIR					; Default working dir for tasks 
    Global $tcCOMMENT					; Default comment for tasks 
    Global $tcTASKCODES					; Task mnemonic codes 
    Global $tcTRIGCODES					; Trigger mnemonic codes 
    Global $tcLASTERRMSG				; Last error message from EXE - blank if no error 
    Global $tcMONTHS					; Array of Month names 
    Global $tcDAYS					; Array of Day names 
 
    $tcVERSION = '3.0b'
 
    ; ===================================================================== 
    ; START OF USER-DEFINED VALUES ======================================== 
 
    ; Define OUTPUT - Use '' to send command output to console, 'NUL:' to discard, 
    ; or define a filepath to log it. Generally used only for debugging. 
    $tcOUTPUT = 'NUL:'
 
    ; Define the path to the tasks command. This should be simply 'schtasks.exe' 
    ; if it is in the system PATH. 
    $tcEXE = 'schtasks.exe'
 
    ; Define tcMAXTRIGGERS - how many triggers per event will be managed 
    $tcMAXTRIGGERS = 10
 
    ; Default working directory 
    $tcWORKDIR = 'C:\'
 
    ; Default comment 
    $tcCOMMENT = 'Created with tcLib ver ' + tcLibVer()
 
    ; END OF USER-DEFINED VALUES ========================================== 
    ; ===================================================================== 
 
 
 
    ; ===================================================================== 
    ; Task & Trigger Mnemonics - DO NOT CHANGE THIS DATA! 
    ; ===================================================================== 
 
    ; Used by tcDefineTask function - linear array of 3-char mnemonics 
    $tcTASKCODES = 'APPPRMWKDCMTCTRPRIMRTIDLDSBKGBRLOSRQDWDSUSSIIKIERIRHIDITVHOEUSRPWD'
     
    ; Used by tcDefineTrigger function - linear array of 3-char mnemonics 
    $tcTRIGCODES = 'SDTEDTSTMDURINTHEDKADDISTYPARG'
 
    ; Task & Trig PARAMS are deprecated in version 3.0 
    ; Used by tcDefineTask and tcSetEvent functions - TASK parameter names 
    ; $tcTASKPARMS = 'ApplicationName',  'Parameters',  'WorkingDirectory',  'Comment',  'Creator',  'Priority',  'MaxRunTime',  'Idle',  'DontStartIfOnBatteries',  'KillIfGoingOnBatteries',  'RunOnlyIfLoggedOn',  'SystemRequired',  'DeleteWhenDone',  'Suspend',  'StartOnlyIfIdle',  'KillOnIdleEnd',  'RestartOnIdleResume',  'Hidden',  'Interactive',  'HaltOnError' 
 
    ; Used by tcDefineTrigger and tcSetEvent functions - TRIGGER parameter names 
    ;$tcTRIGPARMS = 'StartDate', 'EndDate',  'StartTime',  'MinutesDuration',  'MinutesInterval',  'HasEndDate',  'KillAtDuration',  'Disabled',  'Type',  'TypeArguments' 
 
    ; Array of Month and Day Names (element-1 based) 
    $tcMONTHS = '', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
    $tcDAYS = '', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
 
    ; Define the task/trigger arrays 
    Global $a_tcTask[26]
    Global $a_tcTRIG[$tcMAXTRIGGERS - 1]		; $tcMAXTRIGGERS rows of 11 elements' ? 
 
    ;====================================================================== 
 
 
  EndIf
 
  ; create a default start time at the top of the next hour 
  $_D = Split(tcConvert(tcConvert(@DATE + ' ' + Left(@TIME, 2) + ':00:00') + 7200), ' ')
  $_Date = $_D[0]				; get date portion - MM/DD/YYYY 
  $_Time = $_D[1]				; get time portion - HH:MM 
 
  If $_tcFlag
    If $_tcFlag = 1
      ; Load the Task array with null or zero values 
      $a_tcTASK = '','','','','','','','0  0',  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  '',  '',  '',  '',  '',  '',  ''
 
      ; Load the Trigger array with Null values 
      $_aDefaults = '','','','','','','','','','','F'
 
      For $_Idx = 0 to ($tcMAXTRIGGERS - 1)       ; 10 Triggers, 0-9 
        $a_tcTRIG[$_Idx] = $_aDefaults
      Next
    Else
      $tcInit = $_Date,'00/00/1900',$_Time,0,0,0,0,0,'RQ','RQ','F'
    EndIf
  Else
 
    ; Initialize the Task array with default values 
    $a_tcTASK = 'RQ', '', $tcWORKDIR, $tcCOMMENT, @USERID, 'NORMAL', '3600000', '10 60', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  'default',  'default',  '',  '',  '',  '',  ''
 
 
    ; Initialize the Trig array with the 10 default values, plus a 'configured' flag 
    $_aDefaults = $_Date,'00/00/1900',$_Time,0,0,0,0,0,'RQ','RQ','F'
 
    ; Load the temp array into each index of a 10x11 array 
    For $_Idx = 0 to ($tcMAXTRIGGERS - 1)
        $a_tcTRIG[$_Idx] = $_aDefaults
    Next
 
  EndIf 
 
  Exit 0
 
EndFunction
 
 
 
; adapted from TimeConvert(), returning the format required for tcLib 
Function tcConvert($_CValue)
 
  Dim $_			; generic counter / increment 
  Dim $_Return			; value calculated by the engine to return to the calling routine 
  Dim $_Date, $_Time		; values used by the Date to cTime routine 
  Dim $_A, $_B, $_C, $_D, $_E	; intermediate variables used in the calendar calculation 
 
  ; perform the time conversion 
  If $_CValue + 0 = $_CValue					; convert cTime to Date/Time 
 
    $_ = $_CValue
    Dim $_CValue[5]						; Prepare CValue array to hold date/time components 
    $_CValue[5] = $_
 
    $_CValue[2]  = Int($_CValue[5]  / 86400)			; Days for DATE part 
    $_CValue[5]  = $_CValue[5] - (86400.0 * $_CValue[2])	; Remaining seconds for TIME part 
    If $_CValue[5] < 0
      $_CValue[2] =$_CValue[2] - 1				; Adjust for negative cTime values 
    EndIf
    $_CValue[2]  = $_CValue[2] + 719163
 
    $_E          = $_CValue[2] + 306				; Process m/d/y values, accounting for calendar changes 
    $_D          = 100 * $_E - 25				; and leap years 
    $_A          = $_D / 3652425
    $_B          = $_A - $_A / 4
    $_CValue[0]  = (100 * $_B + $_D) / 36525
    $_C          = $_B + $_E - 365 * $_CValue[0] - $_CValue[0] / 4
    $_CValue[1]  = (5 * $_C + 456) / 153
    $_CValue[2]  = $_C - (153 * $_CValue[1] - 457) / 5
 
    If $_CValue[1] > 12						; More than 12 months? 
      $_CValue[0] = $_CValue[0] + 1				; Add a year 
      $_CValue[1] = $_CValue[1] - 12				; subtract 12 months 
    EndIf
 
    $_CValue[3]  = Int($_CValue[5]  / 3600)
    $_CValue[4]  = Int(($_CValue[5]  - $_CValue[3] * 3600) / 60)
    $_CValue[5]  = $_CValue[5] - Int($_CValue[3] * 3600) - $_CValue[4] * 60
 
    ; deal with negative cTime values 
    If $_CValue[5] < 0
      $_CValue[5] = 60 + $_CValue[5]
      $_CValue[4] = $_CValue[4] - 1
    EndIf
    If $_CValue[4] < 0
      $_CValue[4] = 60 + $_CValue[4]
      $_CValue[3] = $_CValue[3] - 1
    EndIf
    If $_CValue[3] < 0
      $_CValue[3] = 24 + $_CValue[3]
    EndIf
 
    ; format the return string 
    $_Return ='' + right('00'+ $_CValue[1], 2) + '/' + right('00' + $_CValue[2], 2) + '/' + $_CValue[0]
    $_Return = $_Return + ' ' + right('00' + $_CValue[3], 2) + ':' + right('00' + $_CValue[4], 2) ; + ':' + right('00'+$_CValue[5] , 2) 
 
  Else							; Convert Date/Time to cTime 
 
    ; convert to array & verify correct # of fields 
    $_CValue = Split(Join(Split(Join(Split($_CValue + ':0', '/'), ' '), ':'), ' '), ' ', 6)
    If UBound($_CValue) <> 5 Exit 87 EndIf	; Bad date/time format! 
 
    ; Check for M/D/Y instead of Y/M/D 
    If Len($_CValue[2]) = 4
      $_ = $_CValue[2]			; save year 
      $_CValue[2] = $_CValue[1]		; Move Day 
      $_CValue[1] = $_CValue[0]		; Move Month 
      $_CValue[0] = $_			; Move Year 
    EndIf
 
 
    ; convert to numeric values 
    For $_ = 0 to 5 $_CValue[$_] = Val($_CValue[$_]) Next
    If $_CValue[1] < 3
      $_CValue[1] = $_CValue[1] + 12
      $_CValue[0] = $_CValue[0] - 1
    EndIf
 
    $_Date = 1.0 * ($_CValue[2]) + (153 * $_CValue[1] - 457) / 5 + 365 * $_CValue[0] + $_CValue[0] / 4 - $_CValue[0] / 100 + $_CValue[0] / 400 - 306
    $_Time = (Val(CDbl($_CValue[3])) * 3600) + (Val($_CValue[4]) * 60) + Val($_CValue[5])
    $_Return = (($_Date - 719163) * 86400 + $_Time)
  EndIf
 
  ; Return the value 
  $tcConvert = $_Return
  Exit 0
 
EndFunction
 
 
 
; tcLogic - support function 
; Convert True/False to 1/0, $_Mod can invert the logic 
Function tcTextToBool($_Value, OPTIONAL $_Mod)
 
  $tcTextToBool = IIf($_Value = 'True', 1, 0)
  If $_Mod $tcTextToBool = Not $tcTextToBool EndIf
 
  Exit 0
 
EndFunction
 
 
 
; Converts a boolean value to "true" or "false" strings 
Function tcBoolToText($_Value)
 
  $tcBoolToText = IIf($_Value, 'true', 'false')
  Exit 0
 
EndFunction
 
 
 
; Accepts a date + time string in YYYY/MM/DD HH:MM[:ss] 
; and returns it in a YYYY-MM-YYTHH:MM format 
Function tcDTFormat($_DateTime)
 
  $_DateTime = Split($_DateTime, ' ')
 
  $_DateTime[0] = Join(Split($_DateTime[0], '/'), '-')
  If InStr($_DateTime[0], '-') = 3
    $_DateTime[0] = Split($_DateTime[0], '-')
    $_DateTime[0] = $_DateTime[0][2], $_DateTime[0][0],$_DateTime[0][1]
    $_DateTime[0] = Join($_DateTime[0], '-')
  EndIf
  $_DateTime[1] = Left($_DateTime[1], 5)
  $tcDTFormat = Join($_DateTime, 'T')
  Exit 0
 
EndFunction
 
 
 
; Converts the source value to seconds in "PT#S" format 
Function tcTimeFormat($_Val, $_Unit)
 
  Select
    Case $_Unit = 'MS'		; convert ms to seconds (/1000) 
      $_Val = 1.0 * $_Val / 1000.0
    Case $_Unit = 'M'		; convert minutes to seconds (*60) 
      $_Val = 60.0 * $_Val
    Case $_Unit = 'H'		; convert hours to seconds (*3600) 
      $_Val = 3600.0 * $_Val
  EndSelect
 
  $tcTimeFormat = 'PT' + $_Val + 'S'
 
  Exit 0
 
EndFunction
 
 
 
; tcTimeVal - support fucntion 
; converts YYYY-MM-DDThh:mm:ss format to MM/DD/YYYY HH:MM:SS 
; converts P values to Seconds, then to desired format 
; Mod can be D (days), H (hours), M (minutes), or S (seconds) 
; Returns ms if Mod is not specified. 
; Input format can be YYYY-MM-DDTHH:MM:SS or PnYnMnDTnHnMnS 
Function tcTimeVal($_Value, OPTIONAL $_Mod)
 
  Dim $_Secs				; ms accumulator 
  Dim $_V				; intermediate value 
  Dim $_aDate				; Date array for resequencing 
  Dim $_TCode				; Time code 
  Dim $_IsTime				; Flag indicating Time 
  Dim $_C				; working char 
 
  $tcTimeVal = 0
  $_IsTime = 0
  $_Secs = 0
 
  ; Validate input - must contain "T" in pos 11 or begin with "P" 
  If SubStr($_Value, 11, 1) <> 'T' And Left($_Value, 1) <> 'P'
    Exit 87
  EndIf
 
  ; simple date reformat operation 
  If SubStr($_Value, 11, 1) = 'T'
    $_V = Split($_Value, 'T')
    $_aDate = Split($_V[0], '-')
    $_V[0] = $_aDate[1] + '/' + $_aDate[2] + '/' + $_aDate[0]
    $tcTimeVal = Join($_V, ' ')
    Exit 0
  EndIf
 
  ; trim the leading "P" character, then enumerate the string 
  ; looking for numeric values followed by type codes. When the 
  ; "T" code is found, flip the flag so "M" represents minutes 
  ; instead of Months. 
  $_Value = SubStr($_Value, 2)		; trim leading "P" char 
  While Len($_Value) > 0
 
    If Left($_Value, 1) = 'T'		; day or time 
      $_Value = SubStr($_Value, 2)	; trim leading char 
      $_IsTime = 1
    EndIf
 
    $_C = Left($_Value, 1)
    $_Value = SubStr($_Value, 2)	; trim leading char 
 
    While Not InStr('YMWDHMS', $_C)
      $_V = '' + $_V + $_C
      $_C = Left($_Value, 1)
      $_Value = SubStr($_Value, 2)	; trim leading char 
    Loop
    $_V = Val($_V)
    $_TCode = $_C
 
    ; Have a value, convert it to seconds and sum 
    Select
      Case $_TCode = 'Y'
        $_V = 86400.0 * 365.25 * $_V	; Years 
      Case $_TCode = 'M' and Not $_IsTime
        $_V = 86400.0 * 30.4375 * $_V	; Months (averaged) 
      Case $_TCode = 'W'
        $_V = 86400.0 * 7.0 * $_V	; Weeks 
      Case $_TCode = 'D'
        $_V = 86400.0 * $_V		; Days 
      Case $_TCode = 'H'
        $_V = 3600.0 * $_V		; Hours 
      Case $_TCode = 'M' and $_IsTime
        $_V = 60.0 * $_V		; Minutes 
      Case $_TCode = 'S'
        $_V = 1.0 * $_V			; Seconds 
    EndSelect
    $_Secs = $_Secs + $_V
    $_V = 0				; reset value 
  Loop
 
  $_Value = $_Secs			; set default return 
 
  ; convert seconds to desired format - Days, Hours, Minutes, or ms 
  Select
    Case $_Mod = 'D'			; Days 
      $_Value = 1.0 * $_Secs / 86400.0
    Case $_Mod = 'H'			; Hours 
      $_Value = 1.0 * $_Secs / 3600.0
    Case $_Mod = 'M'			; Minutes 
      $_Value = 1.0 * $_Secs / 60.0
    Case $_Mod = ''			; ms 
      $_Value = 1.0 * $_Secs * 1000.0
  EndSelect
 
 
  $tcTimeVal = $_Value
  Exit 0
 
EndFunction
 
 
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcDefineTask(TaskParms) 
; 
;ACTION         Loads the $a_tcTASK array with the task parameter pairs. 
;               The parameter pairs consist of a 3-character mnemonic, '=', 
;               and a value. Mnemonics represent the 20 parameter names, 
;               and are identified in the table below. 
; 
;SYNTAX         tcDefineTask('TaskAry', TaskParm=val,...) 
; 
;PARAMETERS     TaskParm - List of mnemonic=Value Parameter pairs, comma-delimited 
; 
;            Mnemonic  Parameter Name           Data Type 
;               APP : ApplicationName           String - command to run 
;               PRM : Parameters                String - app parameters 
;               WKD : WorkingDirectory          String  
;               CMT : Comment                   String 
;               CTR : Creator                   String - Defaults to current user 
;               PRI : Priority                  String: IDLE, NORMAL, HIGH, REALTIME 
;               MRT : MaxRunTime                Integer (ms) 
;               IDL : Idle                      Integer # # (wait & deadline min) 
;               DSB : DontStartIfOnBatteries    Boolean 
;               KGB : KillIfGoingOnBatteries    Boolean 
;               RLO : RunOnlyIfLoggedOn         Boolean 
;               SRQ : SystemRequired            Boolean 
;               DWD : DeleteWhenDone            Boolean 
;               SUS : Suspend                   Boolean 
;               SII : StartOnlyIfIdle           Boolean 
;               KIE : KillOnIdleEnd             Boolean 
;               RIR : RestartOnIdleResume       Boolean 
;               HID : Hidden                    Boolean 
;               ITV : Interactive               Boolean (currently unsupported by JT) 
;               HOE : HaltOnError               Boolean (currently unsupported by JT) 
;               USR : User Account              String 
;               PWD : User Account Password     String 
; 
;REMARKS        This function parses the parameter=value pairs and loads the  
;               value into the correct array position. Parameter pairs are separated 
;               by whitespace. Any character is permitted in the value portion, but 
;               equal signs (=) must be escaped as '=='. 
; 
;RETURNS        1 on success, 0 on failure - sets @ERROR if not initialized or invalid mnemonic 
; 
;DEPENDENCIES   none 
; 
;EXAMPLE        tcDefineTask('APP=kix32.exe PRM=$arg==3 WKD=C:\TEMP') 
; 
Function tcDefineTask($_tcTaskParmArgs)
 
  Dim $_Parm					; Parameter enumerator 
  Dim $_Code					; mnemonic 
  Dim $_Cidx					; mnemonic ID 
  Dim $_PVal					; Parameter Value 
  Dim $_Invalid					; Validity Flag 
 
  $tcDefineTask = 0
 
  If Not IsDeclared($a_tcTASK)
    Exit 2					; fail if $a_tcTASK not defined! 
  EndIf
 
  ; Isolate the parameter pairs 
  For Each $_Parm in tcSplitParms($_tcTaskParmArgs)
    $_Parm = Trim($_Parm)			; remove leading/trailing spaces 
    $_Code = Left($_Parm, 3)			; get the mnemonic part 
    $_CIdx = InStr($tcTASKCODES, $_Code) - 1	; find the position, zero-based 
    $_Invalid = $_CIdx Mod 3 
    If $_Invalid				; invalid mnemonic 
      Exit 87
    Else					; got valid mnemonic 
      $_CIdx = $_CIdx / 3			; convert to array index 
      $_PVal = SubStr($_Parm, 5)		; get the value part 
      $a_tcTASK[$_CIdx] = $_PVal		; stuff value into array 
    EndIf
  Next
 
  $tcDefineTask = 1
  Exit 0
 
EndFunction
 
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcDefineTrigger(TrigId, TrigParm) 
; 
;ACTION         Loads the $a_tcTRIG array with the trigger parameters. TrigID  
;               specifies one of the 10 (0-9) triggers in the array. The  
;               parameter mnemonics are defined in the table below. 
; 
;SYNTAX         tcDefineTrigger(UsrAry, TrigId, TrigParm=value,...) 
; 
;PARAMETERS     TrigId   - Id (index) of the trigger 
;               TrigParm - List of mnemonic=Value Parameter pairs, comma-delimited 
; 
;            Mnemonic  Parameter Name           Data Type 
;               SDT : StartDate                 Date 
;               EDT : EndDate                   Date 
;               STM : StartTime                 Time 
;               DUR : MinutesDuration           Integer (minutes) 
;               INT : MinutesInterval           Integer (minutes) 
;               HED : HasEndDate                Boolean 
;               KAD : KillAtDuration            Boolean 
;               DIS : Disabled                  Boolean 
;               TYP : Type                      String: DAILY,WEEKLY,ONCE... 
;               ARG : TypeArguments             Various, depends on TYPE 
; 
;               Type		Args			Description 
;               Daily		#			Run every # days 
;               Weekly		#,WeekDays		Run every # weeks on specified days 
;               MonthlyDate	#,Months		Run on # day of defined months 
;               MonthlyDOW	#,Weekdays,Months	Run on defined days of # week of defined months 
; 
;               Weekdays = UMTWRFA for Sunday thru Saturday. Days not defined require a '.' placeholder 
;                         ".M.W.F." represents Mon, Wed, and Fri 
; 
;               Months are 3-letter abbreviations. No spaces in list (JanAprJulOct) 
; 
;REMARKS        This function parses the parameter=value pairs and 
;               loads the value into the correct array position 
;                Any character is permitted in the value portion, but equal 
;               signs (=) must be escaped as '=='. 
; 
;RETURNS        1 on success, 0 on failure - sets @ERROR if not initialized or invalid mnemonic is found 
; 
;DEPENDENCIES   none 
; 
;EXAMPLE        tcDefineTrigger(3, 'STM=21:45 TYP=WEEKLY ARG=1,.M.....') 
;                       Defines trigger #3 to run every Monday at 9:45pm 
; 
; 
Function tcDefineTrigger($_tcTrigId, $_tcTrigParmArgs)
 
  Dim $_Parm					; Parameter enumerator 
  Dim $_Code					; mnemonic 
  Dim $_Cidx					; mnemonic enumerator 
  Dim $_PVal					; Parameter Value 
  Dim $_Invalid					; Validity Flag 
 
  $tcDefineTrigger = 0
 
  If Not IsDefined($a_tcTRIG)
    Exit 2					; fail if not initialized 
  EndIf
 
  ; Isolate the parameter pairs - Mnemonic=Value - from the argument list  
  For Each $_Parm in tcSplitParms($_tcTrigParmArgs)
    $_Parm = Trim($_Parm)			; remove any leading/trailing spaces 
    $_Code = Left($_Parm, 3)			; get the mnemonic part 
    $_CIdx = InStr($tcTRIGCODES, $_Code)-1	; find the position, zero-based 
    $_Invalid = $_CIdx Mod 3 
    If $_Invalid				; invalid mnemonic - return with error 
      Exit 87
    Else					; got a valid mnemonic 
      $_CIdx = $_CIdx / 3			; convert to array index 
      $_PVal = SubStr($_Parm, 5)		; get the value part 
      $a_tcTRIG[$_tcTrigId][$_CIdx] = $_PVal	; stuff value into the array 
    EndIf
  Next
 
  $a_tcTRIG[$_tcTrigId][10] = 'T'		; set flag to show this trigger is 'configured'  
 
  ; Certain Trigger types do not require the TypeArguments value to be set. The 
  ; 'RQ' flag in element 9 is removed automatically for those... 
  If InStr('ONCE,ONIDLE,ATSTARTUP,ATLOGON', $a_tcTRIG[$_tcTrigId][8])
    $a_tcTRIG[$_tcTrigId][9] = ''		; remove ReQuired flag for these Types 
  EndIf
 
  $tcDefineTrigger = 1
  Exit 0
 
EndFunction
 
 
;==================================================================== 
; tcSplitParms() 
; Splits a string of MNM=value sets into an array of MNM=value pairs 
; This allows the value to contain ANY data, except the "=" character 
; If "=" chars are required in the value part, they must be doubled (==). 
 
Function tcSplitParms($_ArgList)
 
  Dim $_aTmp, $_aOut[0]				; Temp array, Output array 
  Dim $_Data					; Processed data element 
  Dim $_I					; index var 
 
  ; Replace "==" with a placeholder 
  $_ArgList = Join(Split($_ArgList, '=='), Chr(6))
 
  ; create a working array split by the "=" character 
  ; first element will be an MNM, second thru next-to-last will be  
  ; "Data MNM", and last will be just "Data" 
  $_aTmp = Split($_ArgList, '=')
 
  ReDim $_aOut[UBound($_aTmp) - 1]		; resize the output array 
 
  ; assemble the output data array 
  $_aOut[0] = $_aTmp[0] + '='			; first MNM 
 
  For $_I = 1 to UBound($_aTmp) - 1		; process the middle element pairs 
    $_aOut[$_I] = Right($_aTmp[$_I], 3)	+ '='
    $_Data = Trim(Left($_aTmp[$_I], Len($_aTmp[$_I]) - 3))
    $_Data = Join(Split($_Data, Chr(6)), '=')
    $_aOut[$_I - 1] = $_aOut[$_I - 1] + $_Data
  Next
 
  ; process the last data element 
  $_Data = Join(Split($_aTmp[$_I], Chr(6)), '=')
  $_aOut[$_I - 1] = $_aOut[$_I - 1] + $_Data
  
  $tcSplitParms = $_aOut
 
  Exit 0
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcGetEvent(Host, TaskName) 
; 
;ACTION         This function loads a pair of arrays with the task and 
;               trigger data for the named event. The arrays should be 
;               initialized with nulls or default values prior to calling 
;               this routine. 
; 
;SYNTAX         $Result = tcGetEvent(Host, TaskName) 
; 
;PARAMETERS     Host     - Name of server to query 
;               Taskname - Name of task to confirm 
; 
;REMARKS        The global arrays defined in tcInit() are used. 
; 
;RETURNS        Status = 1 on success, 0 on error 
;               - Sets @ERROR; loads global arrays  
; 
;DEPENDENCIES   tcTextToBool and tcTimeVal support UDFs (included herein) 
; 
;EXAMPLES       tcGetEvent('server', 'MyTask') 
;                       Loads TaskArray with the task parameters, and 
;                       TrigArray with the trigger parameters from the  
;                       'MyTask' event on \\server. 
; 
Function tcGetEvent($_tcHost, $_tcTaskName)
 
  Dim $_Cmd							; command string 
  Dim $_P							; Index pointer 
  Dim $_A, $_B, $_C, $_D					; Loop Index vars 
  Dim $_aTime							; Array of Date/Time data 
  Dim $_Comma							; Null or Comma 
  Dim $_Interval						; Interval value 
  Dim $_Days, $_Months						; Days & Months string 
  Dim $_TrigID							; Trigger ID 
  Dim $_aXML							; Array of XML data 
 
  $tcGetEvent = 0						; default return (fail) 
  $_TrigID = -1							; initial trigger index 
  $a_tcTASK[12] = 0						; TASK: Delete When Done default 
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
  If Not IsDeclared($a_tcTASK)
    Exit 2							; fail if not defined! 
  EndIf
  
; /Query /XML /S hostname /TN "task name" dumps all task data in XML format 
; This returns all required data in a single call 
  $_Cmd = '%COMSPEC% /C ' + $tcEXE + ' /Query /XML /S ' + $_tcHost + ' /TN "' + $_tcTaskName + '"'
  $_aXML = tcExecCmd($_Cmd)
  If @ERROR Exit @ERROR EndIf
 
  ; Trim the resulting array to remove leading whitespace 
  For $_P = 0 to UBound($_aXML)
    $_aXML[$_P] = Trim($_aXML[$_P])
  Next
  
  For $_P = 0 to UBound($_aXML)
    Select
      ; Get Registration Info (author, description 
      Case InStr($_aXML[$_P], '<RegistrationInfo>') = 1
        $_P = $_P + 1						; next value 
        $_A = 1
        While $_A
          Select
 
            Case InStr($_aXML[$_P], '<Description>') = 1
              $a_tcTASK[3] = Split(SubStr($_aXML[$_P], 14), '<')[0]
 
            Case InStr($_aXML[$_P], '<Author>') = 1
              $a_tcTASK[4] = Split(SubStr($_aXML[$_P], 9), '<')[0]
 
            Case InStr($_aXML[$_P], '</RegistrationInfo>') = 1
              $_A = 0						; clear section tag 
 
          EndSelect
          $_P = $_P + 1						; next value 
        Loop
 
        $_P = $_P - 1						; Prior value 
 
 
      ; Triggers can be one of CalendarTrigger, BootTrigger, IdleTrigger, TimeTrigger, 
      ; EventTrigger, LogonTrigger 
      Case InStr($_aXML[$_P], '<Triggers>') = 1
        $_P = $_P + 1						; next value 
        $_A = 1
        While $_A
          Select
 
            ; "B" level process - CalendarTrigger 
            Case InStr($_aXML[$_P], '<CalendarTrigger>') = 1
              $_P = $_P + 1					; next value 
              $_B = 1
              $_TrigID = $_TrigID + 1				; next Trigger 
              ; Preload trigger defaults 
              $a_tcTRIG[$_TrigID] = '', '', '', 0, 0, 0, 0, 0, '', '', 'T'
              $_Interval = ''
              $_Days = '.......'
              $_Months = ''
 
              While $_B
                Select
 
                  Case InStr($_aXML[$_P], '<StartBoundary>') = 1
                     $_aTime = Split(tcTimeVal(Split(SubStr($_aXML[$_P], 16), '<')[0]))
                     $a_tcTRIG[$_TrigID][0] = $_aTime[0]	; Start Date 
                     $a_tcTRIG[$_TrigID][2] = $_aTime[1]	; Start Time 
 
                  Case InStr($_aXML[$_P], '<EndBoundary>') = 1
                     $_aTime = Split(tcTimeVal(Split(SubStr($_aXML[$_P], 14), '<')[0]))
                     $a_tcTRIG[$_TrigID][1] = $_aTime[0]	; End Date 
                     $a_tcTRIG[$_TrigID][5] = IIf($_aTime[0] <> '', 1, 0)
 
                  Case InStr($_aXML[$_P], '<Enabled>') = 1 ; not disabled status - invert Enabled flag 
                    $a_tcTRIG[$_TrigID][7] = tcTextToBool(Split(SubStr($_aXML[$_P], 10), '<')[0], 1)
 
; process ScheduleByDay, ScheduleByWeek, ScheduleByMonth, & ScheduleByMonthDayOfWeek (Level C) 
 
                  ; "C" level process - ScheduleByDay 
                  Case InStr($_aXML[$_P], '<ScheduleByDay>') = 1
                    $_P = $_P + 1				; next value 
                    $_C = 1
                    $a_tcTRIG[$_TrigID][8] = 'Daily'
 
                    While $_C
                      Select
 
                        Case InStr($_aXML[$_P], '<DaysInterval>') = 1 	;  
                          $a_tcTRIG[$_TrigID][9] = Split(SubStr($_aXML[$_P], 15), '<')[0]
 
			; process Day of Week, Months, Day of Month (Level D) 
                        Case InStr($_aXML[$_P], '</ScheduleByDay>') = 1
                          $_C = 0				; clear section tag 
                          $_P = $_P - 1				; Prior value 
                      EndSelect
 
                      $_P = $_P + 1				; next value 
                    Loop
                  ; End of "C" level process # # # # # # # # # # # # # # # # # # # # 
 
                  ; "C" level process - ScheduleByWeek 
                  Case InStr($_aXML[$_P], '<ScheduleByWeek>') = 1
                    $_P = $_P + 1				; next value 
                    $_C = 1
                    $a_tcTRIG[$_TrigID][8] = 'Weekly'
 
                    While $_C
                      Select
 
                        Case InStr($_aXML[$_P], '<WeeksInterval>') = 1 	;  
                          $_Interval = Split(SubStr($_aXML[$_P], 16), '<')[0]
 
                        ; "D" level process - DaysOfWeek 
                        Case InStr($_aXML[$_P], '<DaysOfWeek>') = 1
                          $_P = $_P + 1				; next value 
                          $_D = 1
 
                          While $_D
                            Select
 
                              Case InStr($_aXML[$_P], '<Sunday />') = 1 	;  
                                $_Days = 'U' + SubStr($_Days, 2)
                              Case InStr($_aXML[$_P], '<Monday />') = 1 	;  
                                $_Days = Left($_Days, 1) + 'M' + SubStr($_Days, 3)
                              Case InStr($_aXML[$_P], '<Tuesday />') = 1 	;  
                                $_Days = Left($_Days, 2) + 'T' + SubStr($_Days, 4)
                              Case InStr($_aXML[$_P], '<Wednesday />') = 1 	;  
                                $_Days = Left($_Days, 3) + 'W' + SubStr($_Days, 5)
                              Case InStr($_aXML[$_P], '<Thursday />') = 1 	;  
                                $_Days = Left($_Days, 4) + 'R' + SubStr($_Days, 6)
                              Case InStr($_aXML[$_P], '<Friday />') = 1 	;  
                                $_Days = Left($_Days, 5) + 'F' + SubStr($_Days, 7)
                              Case InStr($_aXML[$_P], '<Saturday />') = 1 	;  
                                $_Days = Left($_Days, 6) + 'A'
 
 
			      ; process Day of Week, Months, Day of Month (Level D) 
                              Case InStr($_aXML[$_P], '</DaysOfWeek>') = 1
                                $_D = 0				; clear section tag 
                                $_P = $_P - 1				; Prior value 
                            EndSelect
 
                            $_P = $_P + 1				; next value 
                          Loop
                          $a_tcTRIG[$_TrigID][9] = $_Interval + ',' + $_Days
                        ; End of "D" level process 
 
                        Case InStr($_aXML[$_P], '</ScheduleByWeek>') = 1
                          $_C = 0				; clear section tag 
                          $_P = $_P - 1				; Prior value 
                      EndSelect
 
                      $_P = $_P + 1				; next value 
                    Loop
                  ; End of "C" level process # # # # # # # # # # # # # # # # # # # # 
 
 
                  ; "C" level process - ScheduleByMonth 
                  Case InStr($_aXML[$_P], '<ScheduleByMonth>') = 1
                    $_P = $_P + 1				; next value 
                    $_C = 1
                    $a_tcTRIG[$_TrigID][8] = 'MonthlyDate'
 
                    While $_C
                      Select
 
                        ; "D" level process - Months 
                        Case InStr($_aXML[$_P], '<DaysOfMonth>') = 1
                          $_P = $_P + 1				; next value 
                          $_D = 1
 
                          While $_D
                            Select
 
                              Case InStr($_aXML[$_P], '<Day>') = 1 	;  
                                $_Interval = Split(SubStr($_aXML[$_P], 6), '<')[0]
 
                              Case InStr($_aXML[$_P], '</DaysOfMonth>') = 1
                                $_D = 0				; clear section tag 
                                $_P = $_P - 1				; Prior value 
                            EndSelect
 
                            $_P = $_P + 1				; next value 
                          Loop
                        ; End of "D" level process 
 
                        ; "D" level process - Months 
                        Case InStr($_aXML[$_P], '<Months>') = 1
                          $_P = $_P + 1				; next value 
                          $_D = 1
                          ;$_Months = '' 
 
                          While $_D
                            Select
 
                              Case InStr($_aXML[$_P], '<January />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<February />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<March />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<April />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<May />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<June />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<July />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<August />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<September />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<October />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<November />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<December />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
 
                              Case InStr($_aXML[$_P], '</Months>') = 1
                                $_D = 0				; clear section tag 
                                $_P = $_P - 1				; Prior value 
                            EndSelect
 
                            $_P = $_P + 1				; next value 
                          Loop
                          $a_tcTRIG[$_TrigID][9] = $_Interval + ',' + $_Months
                        ; End of "D" level process 
 
                        Case InStr($_aXML[$_P], '</ScheduleByMonth>') = 1
                          $_C = 0				; clear section tag 
                          $_P = $_P - 1				; Prior value 
                      EndSelect
 
                      $_P = $_P + 1				; next value 
                    Loop
                    $a_tcTRIG[$_TrigID][9] = $_Interval + ',' + $_Months
                  ; End of "C" level process # # # # # # # # # # # # # # # # # # # # 
 
 
                  ; "C" level process - ScheduleByMonthDayOfWeek 
                  Case InStr($_aXML[$_P], '<ScheduleByMonthDayOfWeek>') = 1
                    $_P = $_P + 1				; next value 
                    $_C = 1
                    $a_tcTRIG[$_TrigID][8] = 'MonthlyDOW'
 
                    While $_C
                      Select
 
                        ; "D" level process - Weeks 
                        Case InStr($_aXML[$_P], '<Weeks>') = 1
                          $_P = $_P + 1				; next value 
                          $_D = 1
 
                          While $_D
                            Select
 
                              Case InStr($_aXML[$_P], '<Week>') = 1 	;  
                                $_Interval = $_Interval + $_Comma + Split(SubStr($_aXML[$_P], 7), '<')[0]
                                $_Comma = ','
 
			      ; process Day of Week, Months, Day of Month (Level D) 
                              Case InStr($_aXML[$_P], '</Weeks>') = 1
                                $_D = 0				; clear section tag 
                                $_P = $_P - 1				; Prior value 
                            EndSelect
 
                            $_P = $_P + 1				; next value 
                          Loop
                        ; End of "D" level process 
 
 
 
                        ; "D" level process - DaysOfWeek 
                        Case InStr($_aXML[$_P], '<DaysOfWeek>') = 1
                          $_P = $_P + 1				; next value 
                          $_D = 1
                         ; $_Days = '.......' 
 
                          While $_D
                            Select
 
                              Case InStr($_aXML[$_P], '<Sunday />') = 1 	;  
                                $_Days = 'U' + SubStr($_Days, 2)
                              Case InStr($_aXML[$_P], '<Monday />') = 1 	;  
                                $_Days = Left($_Days, 1) + 'M' + SubStr($_Days, 3)
                              Case InStr($_aXML[$_P], '<Tuesday />') = 1 	;  
                                $_Days = Left($_Days, 2) + 'T' + SubStr($_Days, 4)
                              Case InStr($_aXML[$_P], '<Wednesday />') = 1 	;  
                                $_Days = Left($_Days, 3) + 'W' + SubStr($_Days, 5)
                              Case InStr($_aXML[$_P], '<Thursday />') = 1 	;  
                                $_Days = Left($_Days, 4) + 'R' + SubStr($_Days, 6)
                              Case InStr($_aXML[$_P], '<Friday />') = 1 	;  
                                $_Days = Left($_Days, 5) + 'F' + SubStr($_Days, 7)
                              Case InStr($_aXML[$_P], '<Saturday />') = 1 	;  
                                $_Days = Left($_Days, 6) + 'A'
 
			      ; process Day of Week, Months, Day of Month (Level D) 
                              Case InStr($_aXML[$_P], '</DaysOfWeek>') = 1
                                $_D = 0				; clear section tag 
                                $_P = $_P - 1				; Prior value 
                            EndSelect
 
                            $_P = $_P + 1				; next value 
                          Loop
                        ; End of "D" level process 
 
                        ; "D" level process - Months 
                        Case InStr($_aXML[$_P], '<Months>') = 1
                          $_P = $_P + 1				; next value 
                          $_D = 1
                          $_Months = ''
 
                          While $_D
                            Select
 
                              Case InStr($_aXML[$_P], '<January />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<February />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<March />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<April />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<May />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<June />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<July />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<August />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<September />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<October />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<November />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
                              Case InStr($_aXML[$_P], '<December />') = 1 	;  
                                $_Months = $_Months + Left(Split(SubStr($_aXML[$_P], 2), ' ')[0], 3)
 
                              Case InStr($_aXML[$_P], '</Months>') = 1
                                $_D = 0				; clear section tag 
                                $_P = $_P - 1				; Prior value 
                            EndSelect
 
                            $_P = $_P + 1				; next value 
                          Loop
                        ; End of "D" level process 
 
                        Case InStr($_aXML[$_P], '</ScheduleByMonthDayOfWeek>') = 1
                          $_C = 0				; clear section tag 
                          $_P = $_P - 1				; Prior value 
                      EndSelect
 
                      $_P = $_P + 1				; next value 
                    Loop
                    $a_tcTRIG[$_TrigID][9] = $_Interval + ',' + $_Days + ',' + $_Months
                  ; End of "C" level process # # # # # # # # # # # # # # # # # # # # 
 
                  ; "C" level process - Repetition 
                  Case InStr($_aXML[$_P], '<Repetition>') = 1
                    $_P = $_P + 1				; next value 
                    $_C = 1
 
                    While $_C
                      Select
 
                        Case InStr($_aXML[$_P], '<Duration>') = 1 	;  
                          $a_tcTRIG[$_TrigID][3] = tcTimeVal(Split(SubStr($_aXML[$_P], 11), '<')[0], 'M')
 
                        Case InStr($_aXML[$_P], '<Interval>') = 1 	;  
                          $a_tcTRIG[$_TrigID][4] = tcTimeVal(Split(SubStr($_aXML[$_P], 11), '<')[0], 'M')
 
                        Case InStr($_aXML[$_P], '<StopAtDurationEnd>') = 1 	;  
                          $a_tcTRIG[$_TrigID][6] = tcTextToBool(Split(SubStr($_aXML[$_P], 20), '<')[0])
 
 
			; process Day of Week, Months, Day of Month (Level D) 
                        Case InStr($_aXML[$_P], '</Repetition>') = 1
                          $_C = 0				; clear section tag 
                          $_P = $_P - 1				; Prior value 
                      EndSelect
 
                      $_P = $_P + 1				; next value 
                    Loop
                  ; End of "C" level process # # # # # # # # # # # # # # # # # # # # 
 
 
 
                  Case InStr($_aXML[$_P], '</CalendarTrigger>') = 1
                    $_B = 0					; clear section tag 
                    $_P = $_P - 1				; Prior value 
                EndSelect
 
                $_P = $_P + 1					; next value 
              Loop
            ; End of "B" level process 
 
 
 
            ; "B" level process - TimeTrigger 
            Case InStr($_aXML[$_P], '<TimeTrigger>') = 1
              $_P = $_P + 1					; next value 
              $_B = 1
              $_TrigID = $_TrigID + 1				; next Trigger 
              ; Preload trigger defaults 
              $a_tcTRIG[$_TrigID] = '', '', '', 0, 0, 0, 0, 0, 'Once', '', 'T'
 
              While $_B
                Select
 
                  Case InStr($_aXML[$_P], '<StartBoundary>') = 1
                     $_aTime = Split(tcTimeVal(Split(SubStr($_aXML[$_P], 16), '<')[0]))
                     $a_tcTRIG[$_TrigID][0] = $_aTime[0]	; Start Date 
                     $a_tcTRIG[$_TrigID][2] = $_aTime[1]	; Start Time 
 
                  Case InStr($_aXML[$_P], '<EndBoundary>') = 1
                     $_aTime = Split(tcTimeVal(Split(SubStr($_aXML[$_P], 14), '<')[0]))
                     $a_tcTRIG[$_TrigID][1] = $_aTime[0]	; End Date 
                     $a_tcTRIG[$_TrigID][5] = IIf($_aTime[0] <> '', 1, 0)
 
                  Case InStr($_aXML[$_P], '<Enabled>') = 1 ; not disabled status - invert Enabled flag 
                    $a_tcTRIG[$_TrigID][7] = tcTextToBool(Split(SubStr($_aXML[$_P], 10), '<')[0], 1)
 
                  ; "C" level process - Repetition 
                  Case InStr($_aXML[$_P], '<Repetition>') = 1
                    $_P = $_P + 1				; next value 
                    $_C = 1
 
                    While $_C
                      Select
 
                        Case InStr($_aXML[$_P], '<Duration>') = 1 	;  
                          $a_tcTRIG[$_TrigID][3] = tcTimeVal(Split(SubStr($_aXML[$_P], 11), '<')[0], 'M')
 
                        Case InStr($_aXML[$_P], '<Interval>') = 1 	;  
                          $a_tcTRIG[$_TrigID][4] = tcTimeVal(Split(SubStr($_aXML[$_P], 11), '<')[0], 'M')
 
                        Case InStr($_aXML[$_P], '<StopAtDurationEnd>') = 1 	;  
                          $a_tcTRIG[$_TrigID][6] = tcTextToBool(Split(SubStr($_aXML[$_P], 20), '<')[0])
 
 
			; process Day of Week, Months, Day of Month (Level D) 
                        Case InStr($_aXML[$_P], '</Repetition>') = 1
                          $_C = 0				; clear section tag 
                          $_P = $_P - 1				; Prior value 
                      EndSelect
 
                      $_P = $_P + 1				; next value 
                    Loop
                  ; End of "C" level process # # # # # # # # # # # # # # # # # # # # 
 
 
                  Case InStr($_aXML[$_P], '</TimeTrigger>') = 1
                    $_B = 0					; clear section tag 
                    $_P = $_P - 1				; Prior value 
                EndSelect
 
                $_P = $_P + 1					; next value 
              Loop
            ; End of "B" level process 
 
 
 
            ; "B" level process - BootTrigger 
            Case InStr($_aXML[$_P], '<BootTrigger>') = 1
              $_P = $_P + 1					; next value 
              $_B = 1
              $_TrigID = $_TrigID + 1				; next Trigger 
              ; Preload trigger defaults 
              $a_tcTRIG[$_TrigID] = '', '', '', 0, 0, 0, 0, 0, 'AtStartup', '', 'T'
 
              While $_B
                Select
 
                  Case InStr($_aXML[$_P], '<Enabled>') = 1 ; not disabled status - invert Enabled flag 
                    $a_tcTRIG[$_TrigID][7] = tcTextToBool(Split(SubStr($_aXML[$_P], 10), '<')[0], 1)
 
 
                  Case InStr($_aXML[$_P], '</BootTrigger>') = 1
                    $_B = 0					; clear section tag 
                    $_P = $_P - 1				; Prior value 
                EndSelect
 
                $_P = $_P + 1					; next value 
              Loop
            ; End of "B" level process 
 
 
 
            ; "B" level process - LogonTrigger 
            Case InStr($_aXML[$_P], '<LogonTrigger>') = 1
              $_P = $_P + 1					; next value 
              $_B = 1
              $_TrigID = $_TrigID + 1				; next Trigger 
              ; Preload trigger defaults 
              $a_tcTRIG[$_TrigID] = '', '', '', 0, 0, 0, 0, 0, 'AtLogon', '', 'T'
 
              While $_B
                Select
 
                  Case InStr($_aXML[$_P], '<Enabled>') = 1 ; not disabled status - invert Enabled flag 
                    $a_tcTRIG[$_TrigID][7] = tcTextToBool(Split(SubStr($_aXML[$_P], 10), '<')[0], 1)
 
 
                  Case InStr($_aXML[$_P], '</LogonTrigger>') = 1
                    $_B = 0					; clear section tag 
                    $_P = $_P - 1				; Prior value 
                EndSelect
 
                $_P = $_P + 1					; next value 
              Loop
            ; End of "B" level process 
 
 
            ; End of TRIGGERS processing 
            Case InStr($_aXML[$_P], '</Triggers>') = 1
              $_A = 0						; clear section tag 
          EndSelect
          $_P = $_P + 1						; next value 
        Loop
 
        $_P = $_P - 1						; Prior value 
 
 
 
      ; Settings can be AllowStartOnDemand, RestartOnFailure, MultipleInstancesPolicy, DisallowStartIfOnBatteries, 
      ; StopIfGoingOnBatteries, AllowHardTerminate, StartWhenAvailable, NetworkProfileName, RunOnlyIfNetworkAvailable,  
      ; WakeToRun, Enabled, Hidden, DeleteExpiredTaskAfter, IdleSettings, NetworkSettings, ExecutionTimeLimit,  
      ; Priority, RunOnlyIfIdle, UseUnifiedSchedulingEngine, DisallowStartOnRemoteAppSession 
      ; most are supported/processed 
 
      Case InStr($_aXML[$_P], '<Settings>') = 1
        $_P = $_P + 1						; next value 
        $_A = 1
        While $_A
          Select
 
            Case InStr($_aXML[$_P], '<Priority>') = 1
              $a_tcTASK[5] = Split(SubStr($_aXML[$_P], 11), '<')[0]
 
            Case InStr($_aXML[$_P], '<ExecutionTimeLimit>') = 1
              $a_tcTASK[6] = tcTimeVal(Split(SubStr($_aXML[$_P], 21), '<')[0])
 
            Case InStr($_aXML[$_P], '<DisallowStartIfOnBatteries>') = 1
              $a_tcTASK[8] = tcTextToBool(split(SubStr($_aXML[$_P], 29), '<')[0])
 
            Case InStr($_aXML[$_P], '<StopIfGoingOnBatteries>') = 1
              $a_tcTASK[9] = tcTextToBool(Split(SubStr($_aXML[$_P], 25), '<')[0])
 
            Case InStr($_aXML[$_P], '<DeleteExpiredTaskAfter>') = 1
              $a_tcTASK[12] = 1 ;tcTimeVal(Split(SubStr($_aXML[$_P], 25), '<')[0]) 
 
            Case InStr($_aXML[$_P], '<Enabled>') = 1
              $a_tcTASK[13] = tcTextToBool(Split(SubStr($_aXML[$_P], 10), '<')[0], 1)
 
            Case InStr($_aXML[$_P], '<RunOnlyIfIdle>') = 1
              $a_tcTASK[14] = tcTextToBool(Split(SubStr($_aXML[$_P], 16), '<')[0])
 
            Case InStr($_aXML[$_P], '<Hidden>') = 1
              $a_tcTASK[17] = tcTextToBool(Split(SubStr($_aXML[$_P], 9), '<')[0])
 
            Case InStr($_aXML[$_P], '<IdleSettings>') = 1
              $_P = $_P + 1					; next value 
              $_B = 1
 
              While $_B
                Select
 
                  Case InStr($_aXML[$_P], '<Duration>') = 1
                    $a_tcTASK[7] = Split($a_tcTASK[7], ' ')
                    $a_tcTASK[7][0] = tcTimeVal(Split(SubStr($_aXML[$_P], 11), '<')[0], 'M')
                    $a_tcTASK[7] = Join($a_tcTASK[7], ' ', 2)
 
                  Case InStr($_aXML[$_P], '<WaitTimeout>') = 1
                    $a_tcTASK[7] = Split($a_tcTASK[7], ' ')
                    $a_tcTASK[7][1] = tcTimeVal(Split(SubStr($_aXML[$_P], 14), '<')[0], 'M')
                    $a_tcTASK[7] = Join($a_tcTASK[7], ' ', 2)
 
                  Case InStr($_aXML[$_P], '<StopOnIdleEnd>') = 1
                    $a_tcTASK[15] = tcTextToBool(Split(SubStr($_aXML[$_P], 16), '<')[0])
 
                  Case InStr($_aXML[$_P], '<RestartOnIdle>') =  1
                    $a_tcTASK[16] = tcTextToBool(Split(SubStr($_aXML[$_P], 16), '<')[0])
 
                  Case InStr($_aXML[$_P], '</IdleSettings>') = 1
                    $_B = 0					; clear section tag 
                    $_P = $_P - 1				; Prior value 
                EndSelect
 
                $_P = $_P + 1					; next value 
              Loop
 
 
            Case InStr($_aXML[$_P], '</Settings>') = 1
              $_A = 0						; clear section tag 
          EndSelect
          $_P = $_P + 1						; next value 
        Loop
 
        $_P = $_P - 1						; Prior value 
 
 
 
      ; Principals can be UserId, LogonType, GroupId, DisplayName, RunLevel, ProcessTokenSidType, or RequiredPrivileges 
      ; Only UserID is currently processed 
 
      Case InStr($_aXML[$_P], '<Principals>') = 1
        $_P = $_P + 1						; next value 
        $_A = 1
        While $_A
          Select
            Case InStr($_aXML[$_P], '<UserId>') = 1
              $a_tcTASK[20] = Split(SubStr($_aXML[$_P], 9), '<')[0]
 
            Case InStr($_aXML[$_P], '</Principals>') = 1
              $_A = 0						; clear section tag 
          EndSelect
          $_P = $_P + 1						; next value 
        Loop
 
        $_P = $_P - 1						; Prior value 
 
 
 
      ; Actions can be Exec, ComHandler, SendEmail, and ShowMessage - only Exec currently supported 
 
      Case InStr($_aXML[$_P], '<Actions') = 1
        $_P = $_P + 1						; next value 
        $_A = 1
        While $_A
          Select
            Case InStr($_aXML[$_P], '<Exec>') = 1
              $_P = $_P + 1					; next value 
              $_B = 1
            While $_B
              Select
                Case InStr($_aXML[$_P], '<Command>') = 1
                  $a_tcTASK[0] = Split(SubStr($_aXML[$_P], 10), '<')[0]
 
                Case InStr($_aXML[$_P], '<Arguments>') = 1
                  $a_tcTASK[1] = Split(SubStr($_aXML[$_P], 12), '<')[0]
 
                Case InStr($_aXML[$_P], '<WorkingDirectory>') = 1
                  $a_tcTASK[2] = Split(SubStr($_aXML[$_P], 19), '<')[0]
 
                Case InStr($_aXML[$_P], '</Exec>') = 1
                  $_B = 0					; clear section tag 
              EndSelect
              $_P = $_P + 1					; next value 
            Loop
 
          Case InStr($_aXML[$_P], '</Actions>') = 1
            $_A = 0						; clear section tag 
            $_P = $_P + 1					; next value 
        EndSelect
      Loop
    EndSelect
  Next
 
 
; /Query /S hostname /TN "task name" /V /FO List dumps all task data in list format 
; This is needed to obtain the task status 
  $_Cmd = '%COMSPEC% /C ' + $tcEXE + ' /Query /S ' + $_tcHost + ' /TN "' + $_tcTaskName + '" /V /FO List'
  $_aXML = tcExecCmd($_Cmd)
  If @ERROR Exit @ERROR EndIf
  $a_tcTASK[22] = Trim(Split($_aXML[7], ':')[1])
  $a_tcTASK[23] = Trim(Split($_aXML[4], ':')[1])
  $a_tcTASK[25] = Trim(Split($_aXML[8], ':')[1])
  $a_tcTASK[26] = Trim(Split($_aXML[5], ':')[1])
  $a_tcTASK[22] = IIf($a_tcTASK[22] = 'N/A','Never',$a_tcTASK[22])
 
  $tcGetEvent = 1
  Exit 0
 
EndFunction
 
 
 
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcSetEvent(Host, TaskName) 
; 
;ACTION         Creates or edits a task and associated triggers 
; 
;SYNTAX         $Return = tcSetEvent(Host, TaskName) 
; 
;PARAMETERS     Host     - Name of server to target 
;               Taskname - Name of task to create/edit 
; 
;REMARKS        Created or modifies an event - combination of Task and it's  
;               associated triggers. If a task or trigger already exists, 
;               the function will edit the existing information. 
; 
;		Version 3.0 has limited ability to edit specific triggers. 
;		If the job exists, it will be deleted and recreated instead 
;		of edited. 
; 
;RETURNS        Success/Failure boolean 
; 
;DEPENDENCIES   tcIsTask()              used to determine Create/Edit mode 
;               tcIsTrigger()           used to determine Create/Edit mode 
; 
;EXAMPLES       tcSetEvent('server', 'Clear Logs') 
;                       creates (or edits) a task on \\server called 'Clear Logs,  
;                       using the parameters in the two global arrays. 
; 
Function tcSetEvent($_tcHost, $_tcTaskName)
 
  Dim $_TID						; Trigger ID index 
  Dim $_PRM						; Parameter string 
  Dim $_Creds						; User credentials parameter 
  Dim $_aMods						; array of schedule type modifiers 
  Dim $_Cmd						; command string 
  Dim $_XMLfile						; path to temp file 
  Dim $_Triggers					; Triggers object 
  Dim $_Month						; month name 
  Dim $_aTmp						; temp array 
  Dim $_						; throwaway var 
 
  $tcSetEvent = 0
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
 
  ; make sure the global arrays are declared 
  If Not IsDeclared($a_tcTASK)
    Exit 2						; fail if not defined! 
  EndIf
 
 
  ; TASK / 'Command' is required - fail if not defined 
  If $a_tcTASK[0] = 'RQ'
      Exit 87                       			; 'Command' is required! 
  EndIf
 
 
  ; TRIGGER / 'Type' and 'TypeArgs' are required - fail if undefined 
  For $_PRM = 0 to ($tcMAXTRIGGERS - 1)  		; check all triggers 
    If $a_tcTRIG[$_PRM][10] = 'T'
      If $a_tcTRIG[$_PRM][8] = 'RQ'
        Exit 87
      EndIf
      If $a_tcTRIG[$_PRM][9] = 'RQ'
        Exit 87
      EndIf
    EndIf
  Next
 
 
  ; Insure that boolean values are not blank before writing 
  For $_TID = 8 to 17
    $a_tcTASK[$_TID] = Val($a_tcTASK[$_TID])
  Next
  For $_TID = 0 to 9
    For $_PRM = 3 to 7
      $a_tcTRIG[$_TID][$_PRM] = Val($a_tcTRIG[$_TID][$_PRM])
    Next
  Next
 
  ; Verify numeric parameters are within acceptable limits 
 
  ; << FUTURE SUPPORT >> 
  ; Execution Time Limit (ms) - 1 day / 860400000 ms 
  If $a_tcTASK[6] < 0 		$a_tcTASK[6] = 0 		EndIf
  If $a_tcTASK[6] > 860400000 	$a_tcTASK[6] = 860400000 	EndIf
 
  $_ = Split($a_tcTASK[7], ' ')
  ; Idle Duration (m) - 1 day /  
  If $_[0] < 0 		$_[0] = 0 	EndIf
  If $_[0] > 3600 	$_[0] = 3600 	EndIf
  ; Idle Duration (m) - 1 day /  
  If $_[1] < 0 		$_[1] = 0 	EndIf
  If $_[1] > 3600 	$_[1] = 3600	EndIf
  $a_tcTASK[7] = Join($_, ' ')
 
 
 
  ; set credentials if defined 
  $_Creds = ''                  ; Credential parameter 
  If $a_tcTASK[20] <> '' And $a_tcTASK[21] <> ''
    $_Creds = ' /RU "' + $a_tcTASK[20] + '" /RP "' + $a_tcTASK[21] + '"'
  EndIf
 
 
  ; Create a temporary XML file for the task and triggers 
  $_XMLfile = %TEMP% + '\' + Join(Split($_tcTaskName, ' '), '') + '_' + @PID + '.XML'
 
 
  ; Define command to create new task event from XML file 
  $_Cmd = '%COMSPEC% /C ' + $tcEXE + ' /CREATE /S ' + $_tcHost + ' /TN "' + $_tcTaskName + '" /XML "' + $_XMLfile + '"' + $_Creds
 
 
  ; Build the XML format file ========================= 
  $_ = RedirectOutput($_XMLfile)
 
  '<?xml version="1.0" encoding="UTF-16"?>' @CRLF
 
  '<Task version="1.1" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">' @CRLF
 
  '  <RegistrationInfo>' @CRLF
 
  '    <Author>' + $a_tcTASK[4] + '</Author>' @CRLF
 
  '    <Description>' + $a_tcTASK[3] + '</Description>' @CRLF
 
  '  </RegistrationInfo>' @CRLF
 
  $_Triggers = '  <Triggers>' + @CRLF
 
  ; create each of the defined triggers 
  For $_TID = 0 to ($tcMAXTRIGGERS - 1)			; process each defined trigger 
    If $a_tcTRIG[$_TID][10] = 'T' 
      $_Triggers					; start <Triggers> section 
      $_Triggers = ''					; clear it so it is only output once 
 
      ; Output syntax will depend upon the trigger type stored in element 8 
      ; Split the trigger tpye modifiers into an array 
      $_aMods = Split($a_tcTRIG[$_TID][9] + ',,,', ',')	; insure at least 4 array elements 
 
      ; create the various types of triggers 
      Select
 
        ; ==================================================================================================== 
        ; =========================                       DAILY                      ========================= 
        ; ==================================================================================================== 
        ; Run at a specified time every # of days 
        Case $a_tcTRIG[$_TID][8] = 'Daily'
          '    <CalendarTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          tcRepetition($_TID)
          '      <StartBoundary>'
          tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][0] + ' ' + $a_tcTRIG[$_TID][2]))) + ':00'
          '</StartBoundary>' + @CRLF
          If $a_tcTRIG[$_TID][5]			; has End Date 
            '      <EndBoundary>'
            tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][1] + ' ' + $a_tcTRIG[$_TID][2]))) + ':59'
            '</EndBoundary>' + @CRLF
          EndIf
          '      <ScheduleByDay>' + @CRLF
          '        <DaysInterval>' + $_aMods[0] + '</DaysInterval>' + @CRLF
          '      </ScheduleByDay>' + @CRLF
          '    </CalendarTrigger>' + @CRLF
 
        ; ==================================================================================================== 
        ; =========================                      WEEKLY                      ========================= 
        ; ==================================================================================================== 
 
        ; Run at a specified time on the specified days, every # of weeks 
        Case $a_tcTRIG[$_TID][8] = 'Weekly'
          '    <CalendarTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          tcRepetition($_TID)
          '      <StartBoundary>'
          tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][0] + ' ' + $a_tcTRIG[$_TID][2]))) + ':00'
          '</StartBoundary>' + @CRLF
          If $a_tcTRIG[$_TID][5]			; has End Date 
            '      <EndBoundary>'
            tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][1] + ' ' + $a_tcTRIG[$_TID][2]))) + ':59'
            '</EndBoundary>' + @CRLF
          EndIf
          '      <ScheduleByWeek>' + @CRLF
          '        <WeeksInterval>' + $_aMods[0] + '</WeeksInterval>' + @CRLF
          '        <DaysOfWeek>' + @CRLF
          For $_ = 1 to 7
            If SubStr($_aMods[1], $_, 1) <> '.'
              '          <' + $tcDAYS[$_] + ' />' + @CRLF
            EndIf
          Next
          '        </DaysOfWeek>' + @CRLF
          '      </ScheduleByWeek>' + @CRLF
          '    </CalendarTrigger>' + @CRLF
 
        ; ==================================================================================================== 
        ; =========================                   MONTHLY DATE                   ========================= 
        ; ==================================================================================================== 
 
        ; Run at a specified time on the specified day of the month (IE: 15th of May and November) 
        Case $a_tcTRIG[$_TID][8] = 'MonthlyDate'
          '    <CalendarTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          tcRepetition($_TID)
          '      <StartBoundary>'
          tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][0] + ' ' + $a_tcTRIG[$_TID][2]))) + ':00'
          '</StartBoundary>' + @CRLF
          If $a_tcTRIG[$_TID][5]			; has End Date 
            '      <EndBoundary>' + @CRLF
            tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][1] + ' ' + $a_tcTRIG[$_TID][2]))) + ':59'
            '</EndBoundary>' + @CRLF
          EndIf
          '      <ScheduleByMonth>' + @CRLF
          '        <DaysOfMonth>' + @CRLF
          ; Version 2.0 and earlier allowed a single value 1-31 here. Version 3.0 and above allow multiple dates. 
          $_aTmp = Split($_aMods[0], ' ')
          For Each $_ in $_aTmp
            '          <Day>' + $_ + '</Day>' + @CRLF
          Next
          '        </DaysOfMonth>' + @CRLF
 
          '        <Months>' + @CRLF
          While Len($_aMods[1]) > 2
            $_Month = SubStr($_aMods[1], 1, 3)
            $_Month = (InStr('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC', $_Month) + 2) / 3
            '          <' + $tcMONTHS[$_Month] + ' />' + @CRLF
            $_aMods[1] = SubStr($_aMods[1], 4)
          Loop
          '        </Months>' + @CRLF
          '      </ScheduleByMonth>' + @CRLF
          '    </CalendarTrigger>' + @CRLF
 
        ; ==================================================================================================== 
        ; =========================                   MONTHLY DOW                    ========================= 
        ; ==================================================================================================== 
 
        ; Run at a specified time on the specified days, on the specified weeks (IE: second Tuesday of May and November) 
        Case $a_tcTRIG[$_TID][8] = 'MonthlyDOW'
          '    <CalendarTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          tcRepetition($_TID)
          '      <StartBoundary>'
          tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][0] + ' ' + $a_tcTRIG[$_TID][2]))) + ':00'
          '</StartBoundary>' + @CRLF
          If $a_tcTRIG[$_TID][5]			; has End Date 
            '      <EndBoundary>'
            tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][1] + ' ' + $a_tcTRIG[$_TID][2]))) + ':59'
            '</EndBoundary>' + @CRLF
          EndIf
          '      <ScheduleByMonthDayOfWeek>' + @CRLF
          '        <Weeks>' + @CRLF
 
          ; Version 2.0 and earlier allowed a single value 1-31 here. Version 3.0 and above allow multiple dates. 
          $_aTmp = Split($_aMods[0], ' ')
          For Each $_ in $_aTmp
            '          <Week>' + $_ + '</Week>' + @CRLF
          Next
 
          '        </Weeks>' + @CRLF
          '        <DaysOfWeek>' + @CRLF
          For $_ = 1 to 7
            If SubStr($_aMods[1], $_, 1) <> '.'
              '          <' + $tcDAYS[$_] + ' />' + @CRLF
            EndIf
          Next
          '        </DaysOfWeek>' + @CRLF
          '        <Months>' + @CRLF
          While Len($_aMods[2]) > 2
            $_Month = SubStr($_aMods[2], 1, 3)
            $_Month = (InStr('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC', $_Month) + 2) / 3
            '          <' + $tcMONTHS[$_Month] + ' />' + @CRLF
            $_aMods[2] = SubStr($_aMods[2], 4)
          Loop
          '        </Months>' + @CRLF
          '      </ScheduleByMonthDayOfWeek>' + @CRLF
          '    </CalendarTrigger>' + @CRLF
 
        ; ==================================================================================================== 
        ; =========================                       ONCE                       ========================= 
        ; ==================================================================================================== 
 
        ; Run at a specified time and date. No repeat. 
        Case $a_tcTRIG[$_TID][8] = 'Once'
          '    <TimeTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          '      <StartBoundary>'
          tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][0] + ' ' + $a_tcTRIG[$_TID][2]))) + ':00'
          '</StartBoundary>' + @CRLF
          '    </TimeTrigger>' + @CRLF
 
        ; ==================================================================================================== 
        ; =========================                      ON IDLE                     ========================= 
        ; ==================================================================================================== 
 
        ; Run when the system enters an idle state 
        Case $a_tcTRIG[$_TID][8] = 'OnIdle'
          '    <IdleTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          If $a_tcTRIG[$_TID][5]			; has End Date 
            '      <EndBoundary>'
            tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][1] + ' ' + $a_tcTRIG[$_TID][2]))) + ':59'
            '</EndBoundary>' + @CRLF
          EndIf
          '    </IdleTrigger>' + @CRLF
 
        ; ==================================================================================================== 
        ; =========================                    AT STARTUP                    ========================= 
        ; ==================================================================================================== 
 
        ; Run when the system boots 
        Case $a_tcTRIG[$_TID][8] = 'AtStartup'
          '    <BootTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          If $a_tcTRIG[$_TID][5]			; has End Date 
            '      <EndBoundary>'
            tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][1] + ' ' + $a_tcTRIG[$_TID][2]))) + ':59'
            '</EndBoundary>' + @CRLF
          EndIf
          '    </BootTrigger>' + @CRLF
 
        ; ==================================================================================================== 
        ; =========================                     AT LOGON                     ========================= 
        ; ==================================================================================================== 
 
        ; Run when a user logs in 
        Case $a_tcTRIG[$_TID][8] = 'AtLogon'
          '    <LogonTrigger>' + @CRLF
          '      <Enabled>' + tcBoolToText(Not($a_tcTRIG[$_TID][7])) + '</Enabled>' + @CRLF	; NOT DISABLE! 
          If $a_tcTRIG[$_TID][5]			; has End Date 
            '      <EndBoundary>'
            tcDTFormat(tcConvert(tcConvert($a_tcTRIG[$_TID][1] + ' ' + $a_tcTRIG[$_TID][2]))) + ':59'
            '</EndBoundary>' + @CRLF
          EndIf
          '    </LogonTrigger>' + @CRLF
 
      EndSelect
 
    EndIf
  Next ; TID 
 
  If Not $_Triggers '  </Triggers>' + @CRLF EndIf	; close triggers section 
 
 
  '  <Settings>' + @CRLF
 
  '    <Enabled>' + tcBoolToText(Not($a_tcTASK[13])) + '</Enabled>' + @CRLF ; NOT SUSPEND! 
  If $a_tcTASK[12]
 
    '    <DeleteExpiredTaskAfter>PT0S</DeleteExpiredTaskAfter>' + @CRLF
  EndIf
 
  '    <ExecutionTimeLimit>' + tcTimeFormat($a_tcTASK[6], 'ms') + '</ExecutionTimeLimit>' + @CRLF
 
  '    <Hidden>' + tcBoolToText($a_tcTASK[17]) + '</Hidden>' + @CRLF
 
;  '    <WakeToRun>' + tcBoolToText($a_tcTASK[99]) + '</WakeToRun>' + @CRLF 
 
  '    <DisallowStartIfOnBatteries>' + tcBoolToText($a_tcTASK[8]) + '</DisallowStartIfOnBatteries>' + @CRLF
 
  '    <StopIfGoingOnBatteries>' + tcBoolToText($a_tcTASK[9]) + '</StopIfGoingOnBatteries>' + @CRLF
 
  '    <RunOnlyIfIdle>' + tcBoolToText($a_tcTASK[14]) + '</RunOnlyIfIdle>' + @CRLF
  If $a_tcTASK[5] = Val($a_tcTASK[5])
    $_ = $a_tcTASK[5]
  Else
               ;01234567890 
    $_ = InStr('R..H...N..I', Left($a_tcTASK[5], 1))
    If $_ = 0 $_ = 8 EndIf				; handle unspecified 
    $_ = $_ - 1						; adjust to zero-based 
  EndIf
 
  '    <Priority>' + $_ + '</Priority>' + @CRLF
  $_ = Split($a_tcTASK[7], ' ')
  If UBound($_) = 1 And $a_tcTASK[14]
 
    '    <IdleSettings>' + @CRLF
 
    '      <Duration>' + tcTimeFormat($_[0], 'M') + '</Duration>' + @CRLF
 
    '      <WaitTimeout>' + tcTimeFormat($_[1], 'M') + '</WaitTimeout>' + @CRLF
 
    '      <StopOnIdleEnd>' + tcBoolToText($a_tcTASK[15]) + '</StopOnIdleEnd>' + @CRLF
 
    '      <RestartOnIdle>' + tcBoolToText($a_tcTASK[16]) + '</RestartOnIdle>' + @CRLF
 
    '    </IdleSettings>' @CRLF
  EndIf
 
  '  </Settings>' + @CRLF
 
  '  <Principals>' + @CRLF
 
  '    <Principal>' + @CRLF
 
  '      <LogonType>InteractiveTokenOrPassword</LogonType>' + @CRLF
 
  '    </Principal>' + @CRLF
 
  '  </Principals>' + @CRLF
 
  '  <Actions>' + @CRLF
 
  '    <Exec>' + @CRLF
 
  '      <Command>' + $a_tcTASK[0] + '</Command>' + @CRLF
 
  '      <Arguments>' + $a_tcTASK[1] + '</Arguments>' + @CRLF
 
  '      <WorkingDirectory>' + $a_tcTASK[2] + '</WorkingDirectory>' + @CRLF
 
  '    </Exec>' + @CRLF
 
  '  </Actions>' + @CRLF
  '</Task>' + @CRLF
 
  $_ = RedirectOutput('')
 
  ; If the task event exists, delete first, then create 
  If tcIsTask($_tcHost , $_tcTaskName)
    $_ = tcDelEvent($_tcHost , $_tcTaskName)
    If @ERROR Exit 1000 + @ERROR EndIf
  EndIf
 
  ; create the task event 
  $_ = tcExecCmd($_Cmd)
  If @ERROR						; error while creating task 
    If Not $DEBUG Del $_XMLfile EndIf			; If debug mode, don't delete the XML file 
    If $DEBUG $tcSetEvent = $_XMLfile EndIf		; and return the path to the calling function 
    Exit @ERROR
  EndIf
 
  ; Delete the temp XML file 
  Del $_XMLfile
 
  $tcSetEvent = 1
  Exit 0
 
EndFunction
 
 
 
; support function to handle repetition within tasks  
; If not defined, return immediate 
; otherwise, insert repetition values 
Function tcRepetition($_TID)
 
  If Not $a_tcTRIG[$_TID][4] Exit 0 EndIf
 
  '    <Repetition>' +@CRLF
  If $a_tcTRIG[$_TID][4]
    '      <Interval>'
    tcTimeFormat($a_tcTRIG[$_TID][4], 'M')
    '</Interval>' + @CRLF
  EndIf
  If $a_tcTRIG[$_TID][3]
    '      <Duration>'
    tcTimeFormat($a_tcTRIG[$_TID][3], 'M')
    '</Duration>' + @CRLF
  EndIf
  If $a_tcTRIG[$_TID][6]
    '      <StopAtDurationEnd>'
    tcBoolToText($a_tcTRIG[$_TID][6])
    '</StopAtDurationEnd>' + @CRLF
  EndIf
  '    </Repetition>' +@CRLF
 
 
EndFunction
 
 
 
 
      ; 
;====================================================================== 
; 
;FUNCTION       tcDeleteEvent(host, task) 
; 
;ACTION         Deletes the named task event 
; 
;SYNTAX         $Result = tcDeleteEvent(host, task) 
; 
;PARAMETERS     HOST    - Name of system where action should occur 
;               TASK    - Name of task to delete 
; 
;REMARKS        The named task and all related triggers will be deleted. 
;               The local Task and Trig arrays are not affected. 
; 
;RETURNS        Success/Failure - sets @ERROR from result of the command 
; 
;DEPENDENCIES   None 
; 
;EXAMPLES       tcDelEvent("\\server", "TaskName") 
; 
 
Function tcDelEvent($_tcHOST, $_tcTASK)
 
  Dim $_		; Throwaway var 
  Dim $_Cmd		; command string 
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
  $_Cmd = '%COMSPEC% /C ' + $tcEXE + ' /DELETE /S ' + $_tcHOST + ' /TN "' + $_tcTASK +'" /F'
  $_ = tcExecCmd($_Cmd) 
  $tcDelEvent = Not @ERROR
  Exit @ERROR
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcGetTasks(Host) 
; 
;ACTION         Returns list of task names on the specified host 
; 
;SYNTAX         $TaskList = tcGetTasks(Host) 
; 
;PARAMETERS     Host     - Name of server to query 
; 
;REMARKS        This function loads an arrays with the task names 
;               found on the target host 
; 
;RETURNS        Array containing task names 
;               Array position 0 will contain '-1' on any failure 
; 
;               $aryTasks = tcGetTasks('server') 
;                       Loads $aryTasks with a list of tasks on \\host 
; 
Function tcGetTasks($_tcHost)
 
  Dim $_CMD		; command to run 
  Dim $_aData		; Array of data returned from command 
  Dim $_Tmp		; working data 
  Dim $_Comma		; delimiter 
  Dim $_Flag		; enumeration flag 
  Dim $_Ptr		; array enum pointer 
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
  ; schtasks /Query /S system  
  $_CMD = '%COMSPEC% /C ' + $tcEXE + ' /Query /S ' + $_tcHost
 
  $_aData = tcExecCmd($_CMD)
 
  If @ERROR					; command failed 
    $tcGetTasks = -1, 0				; return -1 in element 0 
    Exit @ERROR
  Else
    ; search for a line containing only "Folder: \", skip next line and read remaining lines until 
    ; a blank line is found, then terminate and return the list 
    $_Flag = 0
    For $_Ptr = 0 to UBound($_aData)
      If $_aData[$_Ptr] = 'Folder: \'
        $_Flag = 1				; found start 
        $_Ptr = $_Ptr + 3			; skip current, header, and separator lines 
      EndIf
      If $_Flag
        If Not $_aData[$_Ptr]
          $_Ptr = UBound($_aData) + 1		; done! 
        Else
          ; Check for "no tasks" message 
          If InStr($_aData[$_Ptr], 'INFO: There are no scheduled tasks prese') = 1
            $_Ptr = UBound($_aData) + 1		; done! 
            $_Tmp = ''				; insure tmp var is empty 
          Else
            $_Tmp = $_Tmp + $_Comma + Trim(Left($_aData[$_Ptr], 40))
            $_Comma = ','
          EndIf
        EndIf
      EndIf
    Next
 
    ; return the Tmp string as an array 
    If $_Tmp <> ''
      $tcGetTasks = Split($_TMP, ',')
    Else
      ReDim $tcGetTasks[0]			; empty, 1-element array 
    EndIF
 
  EndIf		; CMD execution error test 
 
  Exit 0
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcDelTrigger(host, task, trig) 
; 
;ACTION         Deletes the specified task / trigger 
; 
;SYNTAX         $Result = tvDeleteTrigger(host, task, trig [, perm]) 
; 
;PARAMETERS     HOST    - Name of system where action should occur 
;               TASK    - Name of task to delete 
;               TRIG    - Trigger ID to delete (0-9) 
;		PERM	= Flag indicating that the trigger should be removed from the array 
; 
;REMARKS        The specified trigger of the named task will be deleted directly from the task. 
;               The local Task and Trig arrays, if defined, are not affected. 
; 
;		For Version 3.0, there is no ability to delete a specific trigger. This 
;		function will now disable the specified trigger from the array, delete the  
;		task event, and recreate the event without the trigger. The defined trigger 
;		will be re-enabled in the array to emulate the prior result. The optional 
;		PERM flag was also added in version 3.0 to delete the trigger from the array 
;		as well as the stored event. 
; 
;		The ability to save the event requires that the password be defined 
; 
;RETURNS        Success/Failure - sets @ERROR from result command 
; 
;DEPENDENCIES   None 
; 
;EXAMPLES       tcDelTrigger("server", "TaskName", 2) 
;                       Deletes trigger #2 from "TaskName" on \\server 
; 
Function tcDelTrigger($_tcHost, $_tcTask, $_tcTrig, OPTIONAL $_tcPerm)
 
  Dim $_		; Throwaway var 
  Dim $_Err		; Error State 
  Dim $_TState		; current trigger state 
 
  ; Verify that the credentials are defined 
  If $a_tcTASK[20] = 'default' Or $a_tcTASK[20] = '' Or $a_tcTASK[21] = 'default' Or $a_tcTASK[21] = ''
    Exit 5	; no permission to save without credentials 
  EndIf
 
  ; Save the current trigger status 
  $_TState = $a_tcTRIG[$_tcTrig][10]
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
  ; Disable the specified event trigger 
  $a_tcTRIG[$_tcTrig][10] = 'F'
 
  ; Forcibly delete the task event 
  $_ = tcDelEvent($_tcHost, $_tcTask)
  $_Err = @ERROR
 
  If Not $_Err
    ; Create the event without the specified trigger 
    $_ = tcSetEvent($_tcHost, $_tcTask)
    $_Err = IIf(@ERROR, @ERROR, $_Err)
  EndIf
 
  ; Restore the specified event trigger state 
  If Not $_tcPerm
    $a_tcTRIG[$_tcTrig][10] = $_TState 
  EndIf
 
  $tcDelTrigger = Not $_Err
  Exit $_Err
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcIsTask(Host, TaskName) 
; 
;ACTION         Returns "1" if the named task exists, "0" if it doesn't 
; 
;SYNTAX         $Exists = tcIsTask(Host, TaskName) 
; 
;PARAMETERS     Host     - Name of server to query 
;               Taskname - Name of task to confirm 
; 
;REMARKS        This function is used to tell if a task should be  
;               Created or Edited 
; 
;RETURNS        Integer: 1 if found, 0 if not 
; 
;EXAMPLES       If tcIsTask("server", "MyTask") 
;                 ? "MyTask exists!" 
;               EndIF 
; 
Function tcIsTask($_tcHost, $_tcTaskName)
 
  Dim $fAry		; Array returned 
  Dim $fCmd		; command string 
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
; Perform the check, return the value 
  $fCmd = '%COMSPEC% /C ' + $tcEXE + ' /Query /FO Table /NH /S ' + $_tcHost + ' /TN "' + $_tcTaskName + '"'
 
  $fAry = tcExecCmd($fCmd)		; return the array of tasks 
  ; the system may return either "path" or "file", so just check for the common phrase 
  ; The error will be returned in the first array element 
  $tcIsTask = IIf(InStr($fAry[0], 'ERROR: The system cannot find the') = 1, 0, 1)
  Exit 0
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcIsTrigger(Host, TaskName, Trigger) 
; 
;ACTION         Returns "1" if the named trigger exists, "0" if it doesn't 
; 
;SYNTAX         $Exists = tcIsTrigger(Host, TaskName, Trigger) 
; 
;PARAMETERS     Host     - Name of server to query 
;               Taskname - Name of task to check 
;		Trigger  - ID (number) of triger to verify 
; 
;REMARKS        This function is used to tell if a trigger exists and  
;               should be either be Created or Edited. Note that this 
;		function simply checks that a trigger exists in a  
;		particular "slot" - there is no way to associate a 
;		slot with a particular trigger. This function is generally  
;		used to determine if a slot defined in the array also 
; 		is defined in the scheduler. 
; 
;RETURNS        Integer: 1 if found, 0 if not 
; 
;EXAMPLES       If tcIsTrigger("server", "MyTask", 1) 
;                 ? "Trigger 1 exists in task MyTask on \\server!" 
;               EndIF 
; 
Function tcIsTrigger($_tcHost, $_tcTaskName, $_tcTrigger)
 
  Dim $fAry		; Array returned 
  Dim $fCmd		; command string 
  Dim $fTmp		; Tmp value 
 
  ; Assure trigger ID is numeric and 0 or greater 
  $_tcTrigger = Val($_tcTrigger)
  If $_tcTrigger < 0 Exit 87 EndIf
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
  $fCmd = '%COMSPEC% /C ' + $tcEXE + ' /Query /FO List /V /S ' + $_tcHost + ' /TN "' + $_tcTaskName + '" | Find "TaskName: "'
 
  ; run the command and return an array of result data 
  $fAry = tcExecCmd($fCmd)
  $fTmp = UBound($fAry) - 1			; trim trailing blank line from result array element count!	 
 
  $tcIsTrigger = IIf($_tcTrigger <= $fTmp, 1, 0)
  Exit 0
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcSetEventCredentials(Host, TaskName, UserID, Password) 
; 
;ACTION         Sets the credentials for the specified host / task. 
; 
;SYNTAX         tcSetEventCredentials(Host, TaskName, UserName, Password) 
; 
;PARAMETERS     Host     - Name of the target host 
;               TaskName - Name of the task to modify 
;               UserID   - User Name to run the task under 
;               Password - Password for the above account 
; 
;REMARKS        This function sets the account credentials for an existing  
;               task scheduler event. It does not modify the array values. 
;               It is most useful for handling password changes for existing 
;               Task Scheduler events. 
; 
;RETURNS        True on success, False on error 
; 
;DEPENDENCIES   none 
; 
;EXAMPLES       tcSetEventCredentials("server", "MyTask", "my_account", "my_password") 
;               ; Changes the credentials for the named server/event. 
; 
Function tcSetEventCredentials($_tcHost, $_tcEventName, $_tcUID, $_tcPWD)
 
  Dim $_		; Throwaway var 
  Dim $_Cmd		; command string 
 
  $tcSetEventCredentials = 0
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
 
  ; don't continue if task is not valid 
  If Not tcIsTask($_tcHost, $_tcEventName)
    exit 87
  EndIf
 
  ; Build the command 
  $_Cmd = '%ComSpec% /C ' + $tcEXE + '/CHANGE /S ' + $_tcHost
  $_Cmd = $_Cmd + ' /TN "' + $_tcEventName + '"'
  $_Cmd = $_Cmd + ' /RU "' + $_tcUID + '" /RP "' + $_tcPWD +'"'
 
  $_ = tcExecCmd($_CMD)
  $tcSetEventCredentials = Not @ERROR
  Exit @ERROR
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcExecute(Host, TaskName) 
; 
;ACTION         Runs the specified task immediatly 
; 
;SYNTAX         $RC = tcExecute(Host, TaskName) 
; 
;PARAMETERS     Host     - Name of server to query 
;               Taskname - Name of task to execute 
; 
;REMARKS         
; 
;RETURNS        Status of command (True on Success, False on Failure) 
; 
;EXAMPLES       If tcIsTask("server", "MyTask") 
;                 $RC = tcExecute("server", "MyTask") 
;               EndIF 
; 
Function tcExecute($_tcHost, $_tcTaskName)
 
  Dim $_		; Throwaway var 
  Dim $_Cmd		; command string 
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', SubStr($_tcHost, 3), $_tcHost)
  ; $_tcHost = IIf(Left($_tcHost, 2) = '\\', $_tcHost, '\\' + $_tcHost) 
 
; /I - ignore constraints and run immediately 
  $_Cmd = '%COMSPEC% /C ' + $tcEXE + ' /RUN /S ' + $_tcHost + ' /I /TN "' + $_tcTaskName + '"'
  $_ = tcExecCmd($_Cmd)
 
  $tcExecute = Not @ERROR
  Exit @Error
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcTerminate(Host, TaskName) 
; 
;ACTION         Runs the specified task immediatly 
; 
;SYNTAX         $RC = tcTerminate(Host, TaskName) 
; 
;PARAMETERS     Host     - Name of server to query 
;               Taskname - Name of task to terminate 
; 
;REMARKS         
; 
;RETURNS        Status of command (True on Success, False on Failure) 
; 
;EXAMPLES       If tcIsTask("server", "MyTask") 
;                 $RC = tcTerminate("server", "MyTask") 
;               EndIF 
; 
Function tcTerminate($_tcHost, $_tcTaskName)
 
  Dim $_		; Throwaway var 
  Dim $_Cmd		; JT command string 
 
  ; assure proper host name format 
  $_tcHost = IIf(Left($_tcHost, 2) = '\\', $_tcHost, '\\' + $_tcHost)
 
; /SM selects the host, /RJ runs the task 
  $_Cmd = '%COMSPEC% /C ' + $tcEXE + ' /END /S ' + $_tcHost + ' /TN "' + $_tcTaskName + '"'
  $_ = tcExecCmd($_Cmd)
 
  $tcTerminate = Not @ERROR
  Exit @ERROR
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcLoad() 
; 
;ACTION         Loads an event array set from a file 
; 
;SYNTAX         tcLoad(IniFile, Section) 
; 
;PARAMETERS     IniFile - REQUIRED, string - full path to the INI file containing the event data 
; 
;		Section - REQUIRED, string - section name to save the data to, usually the task name 
; 
;REMARKS        Loads an event array from the defined section of an ini file. The section data  
;		is created with the tcSave() function. 
; 
;RETURNS        Result status 
; 
;DEPENDENCIES   none 
; 
Function tcLoad($_IniFile, $_Section)
 
  Dim $_aTmp						; temp array 
  Dim $_I						; Index pointer 
 
  $tcLoad = 0
 
  If Not IsDeclared($a_tcTASK)
    Exit 2						; fail if $a_tcTASK not defined! 
  EndIf
 
  ; Read the task data 
  $_aTmp = ReadProfileString($_IniFile, $_Section, 'TASK')
  If @ERROR Exit @ERROR EndIf
  If Not $_aTmp Exit 87 EndIf
  $_aTmp = Split($_aTmp, Chr(30))
  For $_I = 0 to 19
    $a_tcTASK[$_I] = $_aTmp[$_I]			; load data, skipping credentials and status 
  Next
 
  ; read the trigger data 
  For $_I = 0 to 9	
    ; read and validate the trigger data 
    $_aTmp = ReadProfileString($_IniFile, $_Section, 'TRIG_' + $_I)
    If $_aTmp
      $_aTmp = Split($_aTmp, Chr(30))
      $a_tcTRIG[$_I] = $_aTmp
    EndIf
  Next
 
  ; Set the credentials fields to "default" 
  $a_tcTASK[20] = 'default'
  $a_tcTASK[21] = 'default'
 
  $tcLoad = 1
  Exit 0
 
EndFunction
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcSave() 
; 
;ACTION         Saves an event array set to a file 
; 
;SYNTAX         tcLoad(IniFile, Section) 
; 
;PARAMETERS     IniFile - REQUIRED, string - full path to the INI file containing the event data 
; 
;		Section - REQUIRED, string - section name to save the data to, usually the task name 
; 
;REMARKS        Saves an event array to the defined section of an ini file.  
; 
;RETURNS        Result status 
; 
;DEPENDENCIES   none 
; 
Function tcSave($_IniFile, $_Section)
 
  Dim $_aTmp						; temp array 
  Dim $_Rc						; Return Code catcher 
  Dim $_I						; Index pointer 
 
  $tcSave = 0
 
  If Not IsDeclared($a_tcTASK)
    Exit 2						; fail if $a_tcTASK not defined! 
  EndIf
 
  $_aTmp = $a_tcTASK
  For $_I = 20 to 26
    $_aTmp[$_I] = ''					; clear credentials and status data 
  Next
 
  ; write the task data, first clearing the data 
  $_Rc = WriteProfileString($_IniFile, $_Section, '', '')
  $_Rc = WriteProfileString($_IniFile, $_Section, 'TASK', Join($_aTmp, Chr(30)))
  If @ERROR Exit @ERROR EndIf
 
  ; write the trigger data 
  For $_I = 0 to 9
    If $a_tcTRIG[$_I][10] = 'T'
      $_Rc = WriteProfileString($_IniFile, $_Section, 'TRIG_' + $_I, Join($a_tcTRIG[$_I], Chr(30)))
    EndIf
  Next
 
  $tcSave = 1
  Exit 0
 
EndFunction
 
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcExecCmd() 
; 
;ACTION         Returns an array of output lines from the EXE command 
; 
;SYNTAX         tcExecCmd(CMD) 
; 
;PARAMETERS     CMD - REQUIRED, string - command to execute 
; 
;REMARKS        Executes a command, returns the output as an array, and scans the array 
;		 for errors. Any error detected is returned by the function - the error 
;		 message can be obtained by passing the return code to tcErrMsg() 
; 
;RETURNS        Array - lines of output from command 
; 
;DEPENDENCIES   WSH       
; 
Function tcExecCmd($_Cmd)
 
  Dim $_oSys		; exec pointer 
  Dim $_Output		; output 
  Dim $_Ptr		; Index pointer 
  Dim $_Line
 
  ; Try KixForms first to run silently in KF apps 
  $_oSys = CreateObject('Kixtart.System')	; instantiate KF object 
  If @ERROR
    $_oSys = 0
    ; run the command via WSH instead 
    $_oSys = CreateObject("WScript.Shell").Exec($_Cmd)
    If Not VarType($_oSys)=9 Exit 10 EndIf
    ; capture STDIO & STDERR 
    $_Output = $_oSys.StdOut.ReadAll + $_oSys.StdErr.ReadAll
  Else
    $_Output = $_oSys.Shell($_Cmd,0,3)
  EndIf
 
  ; Handle the intermediate output - normally written to NUL: (discarded) 
  ; but can be sent to console or log file for debugging 
  $_Ptr = RedirectOutput($tcOUTPUT)
  $_Cmd @CRLF
  $_Output @CRLF
  $_Ptr = RedirectOutput('')
 
  ; Convert to array 
  $_Output = Split(Join(Split($_Output,CHR(13)),''),CHR(10))
  $tcExecCmd = $_Output
 
 
  ; Scan output for error messages 
 
  ; Scan the array for error messages such as the sample below 
  ; [FAIL ] ITaskScheduler::Activate(test, IID_ITask) hr=0x80070002 (JT.EXE) 
  ; ERROR: <error text> (SchTasks.EXE) 
  ; aScan was abandoned due to incorrect results being returned. 
  $tcLASTERRMSG = ''				; clear error message 
  For Each $_Line in $_Output
    If InStr(Trim($_Line), 'ERROR:') = 1
      $tcLASTERRMSG = Split($_Line, 'ERROR: ')[1]
      Exit 1
    EndIf
  Next
 
  Exit 0
 
EndFunction
 
 
 
; 
;====================================================================== 
; 
;FUNCTION       tcErrMsg() 
; 
;ACTION         Returns a text string containing the error message for a given scheduler error code 
; 
;SYNTAX         tcErrMsg(Code) 
; 
;PARAMETERS     Code - REQUIRED, integer - error code 
; 
;REMARKS        Looks up the error code and returns the error message string 
; 
;RETURNS        String - error message 
; 
;DEPENDENCIES   None 
; 
Function tcErrMsg($_ErrCode)
 
  Dim $_Base
  $_Base = 4864
 
  If $_ErrCode < $_Base		; return standard error message if less than base value 
    $tcErrMsg = @SERROR
    Exit $_ErrCode
  EndIf
 
  ; return a task-specific error message 
 
  Select
  ; SCHED_S_TASK_READY  
   Case Val($_ErrCode) = $_Base
    $tcErrMsg = 'The task is ready to run at its next scheduled time.'
 
  ; SCHED_S_TASK_RUNNING  
   Case Val($_ErrCode) = $_Base + 1
    $tcErrMsg = 'The task is currently running.'
 
  ; SCHED_S_TASK_DISABLED  
   Case Val($_ErrCode) = $_Base + 2
    $tcErrMsg = 'The task will not run at the scheduled times because it has been disabled.'
 
  ; SCHED_S_TASK_HAS_NOT_RUN  
   Case Val($_ErrCode) = $_Base + 3
    $tcErrMsg = 'The task has not yet run.'
 
  ; SCHED_S_TASK_NO_MORE_RUNS  
   Case Val($_ErrCode) = $_Base + 4
    $tcErrMsg = 'There are no more runs scheduled for this task.'
 
  ; SCHED_S_TASK_NOT_SCHEDULED  
   Case Val($_ErrCode) = $_Base + 5
    $tcErrMsg = 'One or more of the properties that are needed to run this task on a schedule have not been set.'
 
  ; SCHED_S_TASK_TERMINATED  
   Case Val($_ErrCode) = $_Base + 6
    $tcErrMsg = 'The last run of the task was terminated by the user.'
 
  ; SCHED_S_TASK_NO_VALID_TRIGGERS  
   Case Val($_ErrCode) = $_Base + 7
    $tcErrMsg = 'Either the task has no triggers or the existing triggers are disabled or not set.'
 
  ; SCHED_S_EVENT_TRIGGER  
   Case Val($_ErrCode) = $_Base + 8
    $tcErrMsg = 'Event triggers do not have set run times.'
 
  ; SCHED_E_TRIGGER_NOT_FOUND  
   Case Val($_ErrCode) = $_Base + 9
    $tcErrMsg = 'A trigger was not found for the task.'
 
  ; SCHED_E_TASK_NOT_READY  
   Case Val($_ErrCode) = $_Base + 10
    $tcErrMsg = 'One or more of the properties required to run this task have not been set.'
 
  ; SCHED_E_TASK_NOT_RUNNING  
   Case Val($_ErrCode) = $_Base + 11
    $tcErrMsg = 'There is no running instance of the task.'
 
  ; SCHED_E_SERVICE_NOT_INSTALLED  
   Case Val($_ErrCode) = $_Base + 12
    $tcErrMsg = 'The Task Scheduler service is not installed on this computer.'
 
  ; SCHED_E_CANNOT_OPEN_TASK  
   Case Val($_ErrCode) = $_Base + 13
    $tcErrMsg = 'The task object could not be opened.'
 
  ; SCHED_E_INVALID_TASK  
   Case Val($_ErrCode) = $_Base + 14
    $tcErrMsg = 'The object is either an invalid task object or is not a task object.'
 
  ; SCHED_E_ACCOUNT_INFORMATION_NOT_SET  
   Case Val($_ErrCode) = $_Base + 15
    $tcErrMsg = 'No account information could be found in the Task Scheduler security database for the task indicated.'
 
  ; SCHED_E_ACCOUNT_NAME_NOT_FOUND  
   Case Val($_ErrCode) = $_Base + 16
    $tcErrMsg = 'Unable to establish existence of the account specified.'
 
  ; SCHED_E_ACCOUNT_DBASE_CORRUPT  
   Case Val($_ErrCode) = $_Base + 17
    $tcErrMsg = 'Corruption was detected in the Task Scheduler security database; the database has been reset.'
 
  ; SCHED_E_NO_SECURITY_SERVICES  
   Case Val($_ErrCode) = $_Base + 18
    $tcErrMsg = 'Task Scheduler security services are available only on Windows NT.'
 
  ; SCHED_E_UNKNOWN_OBJECT_VERSION  
   Case Val($_ErrCode) = $_Base + 19
    $tcErrMsg = 'The task object version is either unsupported or invalid.'
 
  ; SCHED_E_UNSUPPORTED_ACCOUNT_OPTION  
   Case Val($_ErrCode) = $_Base + 20
    $tcErrMsg = 'The task has been configured with an unsupported combination of account settings and run time options.'
 
  ; SCHED_E_SERVICE_NOT_RUNNING  
   Case Val($_ErrCode) = $_Base + 21
    $tcErrMsg = 'The Task Scheduler Service is not running.'
 
  ; SCHED_E_UNEXPECTEDNODE  
   Case Val($_ErrCode) = $_Base + 22
    $tcErrMsg = 'The task XML contains an unexpected node.'
 
  ; SCHED_E_NAMESPACE  
   Case Val($_ErrCode) = $_Base + 23
    $tcErrMsg = 'The task XML contains an element or attribute from an unexpected namespace.'
 
  ; SCHED_E_INVALIDVALUE  
   Case Val($_ErrCode) = $_Base + 24
    $tcErrMsg = 'The task XML contains a value which is incorrectly formatted or out of range.'
 
  ; SCHED_E_MISSINGNODE  
   Case Val($_ErrCode) = $_Base + 25
    $tcErrMsg = 'The task XML is missing a required element or attribute.'
 
  ; SCHED_E_MALFORMEDXML  
   Case Val($_ErrCode) = $_Base + 26
    $tcErrMsg = 'The task XML is malformed.'
 
  ; SCHED_S_SOME_TRIGGERS_FAILED  
   Case Val($_ErrCode) = $_Base + 27
    $tcErrMsg = 'The task is registered, but not all specified triggers will start the task.'
 
  ; SCHED_S_BATCH_LOGON_PROBLEM  
   Case Val($_ErrCode) = $_Base + 28
    $tcErrMsg = 'The task is registered, but may fail to start. Batch logon privilege needs to be enabled for the task principal.'
 
  ; SCHED_E_TOO_MANY_NODES  
   Case Val($_ErrCode) = $_Base + 29
    $tcErrMsg = 'The task XML contains too many nodes of the same type.'
 
  ; SCHED_E_PAST_END_BOUNDARY  
   Case Val($_ErrCode) = $_Base + 30
    $tcErrMsg = 'The task cannot be started after the trigger end boundary.'
 
  ; SCHED_E_ALREADY_RUNNING  
   Case Val($_ErrCode) = $_Base + 31
    $tcErrMsg = 'An instance of this task is already running.'
 
  ; SCHED_E_USER_NOT_LOGGED_ON  
   Case Val($_ErrCode) = $_Base + 32
    $tcErrMsg = 'The task will not run because the user is not logged on.'
 
  ; SCHED_E_INVALID_TASK_HASH  
   Case Val($_ErrCode) = $_Base + 33
    $tcErrMsg = 'The task image is corrupt or has been tampered with.'
 
  ; SCHED_E_SERVICE_NOT_AVAILABLE  
   Case Val($_ErrCode) = $_Base + 34
    $tcErrMsg = 'The Task Scheduler service is not available.'
 
  ; SCHED_E_SERVICE_TOO_BUSY  
   Case Val($_ErrCode) = $_Base + 35
    $tcErrMsg = 'The Task Scheduler service is too busy to handle your request. Please try again later.'
 
  ; SCHED_E_TASK_ATTEMPTED  
   Case Val($_ErrCode) = $_Base + 36
    $tcErrMsg = 'The Task Scheduler service attempted to run the task, but the task did not run due to one of the constraints in the task definition.'
 
  ; SCHED_S_TASK_QUEUED  
   Case Val($_ErrCode) = $_Base + 37
    $tcErrMsg = 'The Task Scheduler service has asked the task to run.'
 
  ; SCHED_E_TASK_DISABLED  
   Case Val($_ErrCode) = $_Base + 38
    $tcErrMsg = 'The task is disabled.'
 
  ; SCHED_E_TASK_NOT_V1_COMPAT  
   Case Val($_ErrCode) = $_Base + 39
    $tcErrMsg = 'The task has properties that are not compatible with earlier versions of Windows.'
 
  ; SCHED_E_START_ON_DEMAND  
   Case Val($_ErrCode) = $_Base + 40
    $tcErrMsg = 'The task settings do not allow the task to start on demand.'
 
  EndSelect
 
  Exit $_ErrCode	; exit with same value to preserve the setting 
 
EndFunction