farzinmonsef / interesting

0 stars 0 forks source link

ScheduleTasks #4

Open farzinmonsef opened 7 years ago

farzinmonsef commented 7 years ago

ScheduleTasks

farzinmonsef commented 7 years ago

schtasks_help.txt

=======================================

SCHTASKS /Create [/S system [/U username [/P [password]]]] [/RU username [/RP password]] /SC schedule [/MO modifier] [/D day] [/M months] [/I idletime] /TN taskname /TR taskrun [/ST starttime] [/RI interval] [ {/ET endtime | /DU duration} [/K] [/XML xmlfile] [/V1]] [/SD startdate] [/ED enddate] [/IT | /NP] [/Z] [/F]

Description: Enables an administrator to create scheduled tasks on a local or remote system.

Parameter List: /S system Specifies the remote system to connect to. If omitted the system parameter defaults to the local system.

/U   username      Specifies the user context under which SchTasks.exe 
                   should execute.

/P   [password]    Specifies the password for the given user context.
                   Prompts for input if omitted.

/RU  username      Specifies the "run as" user account (user context)
                   under which the task runs. For the system account,
                   valid values are "", "NT AUTHORITY\SYSTEM"
                   or "SYSTEM".
                   For v2 tasks, "NT AUTHORITY\LOCALSERVICE" and 
                   "NT AUTHORITY\NETWORKSERVICE" are also available as well 
                   as the well known SIDs for all three. 

/RP  [password]    Specifies the password for the "run as" user. 
                   To prompt for the password, the value must be either
                   "*" or none. This password is ignored for the 
                   system account. Must be combined with either /RU or
                   /XML switch.

/SC   schedule     Specifies the schedule frequency.
                   Valid schedule types: MINUTE, HOURLY, DAILY, WEEKLY, 
                   MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE, ONEVENT.

/MO   modifier     Refines the schedule type to allow finer control over
                   schedule recurrence. Valid values are listed in the 
                   "Modifiers" section below.

/D    days         Specifies the day of the week to run the task. Valid 
                   values: MON, TUE, WED, THU, FRI, SAT, SUN and for
                   MONTHLY schedules 1 - 31 (days of the month). 
                   Wildcard "*" specifies all days.

/M    months       Specifies month(s) of the year. Defaults to the first 
                   day of the month. Valid values: JAN, FEB, MAR, APR, 
                   MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC. Wildcard "*" 
                   specifies all months.

/I    idletime     Specifies the amount of idle time to wait before 
                   running a scheduled ONIDLE task.
                   Valid range: 1 - 999 minutes.

/TN   taskname     Specifies a name which uniquely
                   identifies this scheduled task.

/TR   taskrun      Specifies the path and file name of the program to be 
                   run at the scheduled time.
                   Example: C:\windows\system32\calc.exe

/ST   starttime    Specifies the start time to run the task. The time 
                   format is HH:mm (24 hour time) for example, 14:30 for 
                   2:30 PM. Defaults to current time if /ST is not 
                   specified.  This option is required with /SC ONCE.

/RI   interval     Specifies the repetition interval in minutes. This is 
                   not applicable for schedule types: MINUTE, HOURLY,
                   ONSTART, ONLOGON, ONIDLE, ONEVENT.
                   Valid range: 1 - 599940 minutes.
                   If either /ET or /DU is specified, then it defaults to 
                   10 minutes.

/ET   endtime      Specifies the end time to run the task. The time format
                   is HH:mm (24 hour time) for example, 14:50 for 2:50 PM.
                   This is not applicable for schedule types: ONSTART, 
                   ONLOGON, ONIDLE, ONEVENT.

/DU   duration     Specifies the duration to run the task. The time 
                   format is HH:mm. This is not applicable with /ET and
                   for schedule types: ONSTART, ONLOGON, ONIDLE, ONEVENT.
                   For /V1 tasks, if /RI is specified, duration defaults 
                   to 1 hour.

/K                 Terminates the task at the endtime or duration time. 
                   This is not applicable for schedule types: ONSTART, 
                   ONLOGON, ONIDLE, ONEVENT. Either /ET or /DU must be
                   specified.

/SD   startdate    Specifies the first date on which the task runs. The 
                   format is mm/dd/yyyy. Defaults to the current 
                   date. This is not applicable for schedule types: ONCE, 
                   ONSTART, ONLOGON, ONIDLE, ONEVENT.

/ED   enddate      Specifies the last date when the task should run. The 
                   format is mm/dd/yyyy. This is not applicable for 
                   schedule types: ONCE, ONSTART, ONLOGON, ONIDLE, ONEVENT.

/EC   ChannelName  Specifies the event channel for OnEvent triggers.

/IT                Enables the task to run interactively only if the /RU 
                   user is currently logged on at the time the job runs.
                   This task runs only if the user is logged in.

/NP                No password is stored.  The task runs non-interactively
                   as the given user.  Only local resources are available.

/Z                 Marks the task for deletion after its final run.

/XML  xmlfile      Creates a task from the task XML specified in a file.
                   Can be combined with /RU and /RP switches, or with /RP 
                   alone, when task XML already contains the principal.

/V1                Creates a task visible to pre-Vista platforms.
                   Not compatible with /XML.

/F                 Forcefully creates the task and suppresses warnings if 
                   the specified task already exists.

/RL   level        Sets the Run Level for the job. Valid values are 
                   LIMITED and HIGHEST. The default is LIMITED.

/DELAY delaytime   Specifies the wait time to delay the running of the 
                   task after the trigger is fired.  The time format is
                   mmmm:ss.  This option is only valid for schedule types
                   ONSTART, ONLOGON, ONEVENT.

/?                 Displays this help message.

Modifiers: Valid values for the /MO switch per schedule type: MINUTE: 1 - 1439 minutes. HOURLY: 1 - 23 hours. DAILY: 1 - 365 days. WEEKLY: weeks 1 - 52. ONCE: No modifiers. ONSTART: No modifiers. ONLOGON: No modifiers. ONIDLE: No modifiers. MONTHLY: 1 - 12, or FIRST, SECOND, THIRD, FOURTH, LAST, LASTDAY.

ONEVENT:  XPath event query string.

Examples: ==> Creates a scheduled task "doc" on the remote machine "ABC" which runs notepad.exe every hour under user "runasuser".

    SCHTASKS /Create /S ABC /U user /P password /RU runasuser
             /RP runaspassword /SC HOURLY /TN doc /TR notepad 

==> Creates a scheduled task "accountant" on the remote machine 
    "ABC" to run calc.exe every five minutes from the specified
    start time to end time between the start date and end date.

    SCHTASKS /Create /S ABC /U domain\user /P password /SC MINUTE
             /MO 5 /TN accountant /TR calc.exe /ST 12:00 /ET 14:00
             /SD 06/06/2006 /ED 06/06/2006 /RU runasuser /RP userpassword

==> Creates a scheduled task "gametime" to run freecell on the 
    first Sunday of every month.

    SCHTASKS /Create /SC MONTHLY /MO first /D SUN /TN gametime 
             /TR c:\windows\system32\freecell

==> Creates a scheduled task "report" on remote machine "ABC"
    to run notepad.exe every week.

    SCHTASKS /Create /S ABC /U user /P password /RU runasuser
             /RP runaspassword /SC WEEKLY /TN report /TR notepad.exe

==> Creates a scheduled task "logtracker" on remote machine "ABC"
    to run notepad.exe every five minutes starting from the
    specified start time with no end time. The /RP password will be
    prompted for.

    SCHTASKS /Create /S ABC /U domain\user /P password /SC MINUTE
             /MO 5 /TN logtracker 
             /TR c:\windows\system32\notepad.exe /ST 18:30
             /RU runasuser /RP

==> Creates a scheduled task "gaming" to run freecell.exe starting
    at 12:00 and automatically terminating at 14:00 hours every day

    SCHTASKS /Create /SC DAILY /TN gaming /TR c:\freecell /ST 12:00
             /ET 14:00 /K
==> Creates a scheduled task "EventLog" to run wevtvwr.msc starting
    whenever event 101 is published in the System channel

    SCHTASKS /Create /TN EventLog /TR wevtvwr.msc /SC ONEVENT
             /EC System /MO *[System/EventID=101] 
==> Spaces in file paths can be used by using two sets of quotes, one
    set for CMD.EXE and one for SchTasks.exe.  The outer quotes for CMD
    need to be double quotes; the inner quotes can be single quotes or
    escaped double quotes:
    SCHTASKS /Create 
       /tr "'c:\program files\internet explorer\iexplorer.exe' 
       \"c:\log data\today.xml\"" ... 

SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN Test Task /TR C:\test.bat /ST 16:30

SchTasks /Create /SC DAILY /TN My_Task1 /TR C:\Users\zkpl9e1\Downloads\Program\ggl.bat /ST 12:28

SchTasks /Create /SC DAILY /TN My_Task1 /TR C:\Users\zkpl9e1\Downloads\Program\ggl.bat /ST 12:28

farzinmonsef commented 7 years ago

schedule.vbs

Option Explicit Const ForWriting = 2 Const ForReading = 1 Const ForAppending = 8 Const TristateFalse = 0

Dim wshshell 'Object provides access to shell Dim fso 'Object provides access to file system Dim gsLogFile 'Location of Log File

Set wshshell = CreateObject("WScript.Shell") Set fso = CreateObject("Scripting.FileSystemObject") gsLogFile = "C:\Users\zkpl9e1\Downloads\Program\ScheduleTasks\" & Left(WScript.ScriptName, Len(WScript.ScriptName)-4) & ".Log"

swritelog " [START]"

'sGetTasks ("Delete", "notepad.exe","","","","") 'sGetTasks "Create", "notepad.exe", "Weekly", "04:00:00", "Weekly_Notepad", "SUN" sGetTasks "Create", "C:\Users\zkpl9e1\Downloads\Program\test.bat", "Daily", "12:22:00", "Daily_test_bat", ""

'sGetTasks ("Delete", "notepad.exe","","","","") 'sGetTasks("Create", "notepad.exe", "Daily", "04:00:00", "Daily_Notepad","") 'sGetTasks ("Delete", "notepad.exe","","","","")

' ' {sGetTasks} Sub to manage all scheduled tasks '

Sub sGetTasks(Action, file, Schedule, startTime, jobname, runday) 'On Error resume Next Dim sTempFile, x, sExec, strLineIn, task Dim strMyArray redim sTaskName(10) swritelog " [Begin sGetTasks]" x = 0 set sExec = wshshell.Exec("schtasks /query /fo csv /nh /v") Do While Not sExec.StdOut.AtEndOfStream swritelog " Do While Not sExec.StdOut.AtEndOfStream " strLineIn = sExec.StdOut.ReadLine() swritelog " No a1: " & strLineIn strMyArray = Split(strLineIn, ",", -1, 1) swritelog " UBound(strMyArray)= " + UBound(strMyArray) If UBound(strMyArray) > 0 Then If InStr(1, replace(strMyArray(11),Chr(34),""), file, 1) > 0 Then sWriteLog " Found Task " & replace(strMyArray(1),Chr(34),"") If x> UBound(sTaskName) Then ReDim Preserve sTaskName(x*2) sTaskName(x) = replace(strMyArray(1), Chr(34),"") x = x + 1 End If End If
Loop ReDim Preserve sTaskName(x) Select Case Action Case "Delete" sWriteLog " Deleting jobs for " & file If UBound(sTaskName)>0 Then For Each Task In sTaskName sWriteLog " Deleting " & Task set sExec = wshshell.Exec("schtasks /delete /tn " & Task & " /f") Do While Not sExec.StdOut.AtEndOfStream swritelog " " & sExec.StdOut.ReadLine() Loop Next else sWriteLog " No Existing jobs found for " & file End If Case "Create" sWriteLog " E1: Creating job for " & file If UBound(sTaskName) = 0 Then sWriteLog " Creating New task for " & file If Schedule = "Daily" Then sWriteLog " G1:"
set sExec = wshshell.Exec("schtasks /create /tn " & jobname & " /tr " & chr(34) & file & Chr (34) & " /sc " & Schedule & " /st " & startTime & " /ru SYSTEM") Else sWriteLog " H1:"
set sExec = wshshell.Exec("schtasks /create /tn " & jobname & " /tr " & chr(34) & file & Chr (34) & " /sc " & Schedule &
" /st " & startTime & " /ru SYSTEM /D " & runday) End If Do While Not sExec.StdOut.AtEndOfStream swritelog " J1: " & sExec.StdOut.ReadLine() Loop else sWriteLog " M1: An Existing job was found for " & file End If End select swritelog " [End sGetTasks]" On Error Goto 0 End Sub

'** ' {sWriteLog} Sub to handle logging of script '**

Sub sWriteLog(asLogText) 'On Error Resume next 'Exit Sub Dim oLogFile Set oLogFile = fso.OpenTextFile(gsLogFile, ForAppending, True) If Err.Number <> 0 Then wscript.Quit(21) End if oLogFile.WriteLine Now & " -- " & asLogText oLogFile.Close Set oLogFile = Nothing End Sub

farzinmonsef commented 7 years ago

schedule1.vbs

strComputer = "." Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\" & strComputer & "\root\cimv2")

Set objNewJob = objWMIService.Get("Win32_ScheduledJob")

errJobCreated = objNewJob.Create ("Notepad.exe", "****123000.000000-420", True , 1 OR 4 OR 16, , , JobID)

farzinmonsef commented 7 years ago

Task1.vbs

Dim objFSO, outFile, wShell Set objFSO = CreateObject("Scripting.FileSystemObject")

Set outFile = objFSO.CreateTextFile("C:\Users\zkpl9e1\Downloads\Program\test.bat", True) outFile.WriteLine "Start www.google.com" outFile.Close

Set wShell = CreateObject ("Wscript.Shell") wShell.Run "cmd SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN 'Test Task' /TR 'C:\Users\zkpl9e1\Downloads\Program\test.bat' /ST 16:30", 0

farzinmonsef commented 7 years ago

Task2.vbs

Function ScheduleTaskWin7(taskName)

' Task Scheduler Scripting Objects
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa383607(v=vs.85).aspx

'------------------------------------------------------------------
' This sample schedules a task to start on a weekly basis.
'------------------------------------------------------------------

' A constant that specifies a weekly trigger.
const TriggerTypeWeekly = 3
' A constant that specifies an executable action.
const ActionTypeExec = 0   

'********************************************************
' Create the TaskService object.
Dim service
Set service = CreateObject("Schedule.Service")
call service.Connect()

'********************************************************
' Get a folder to create a task definition in. 
Dim rootFolder
Set rootFolder = service.GetFolder("c:\Users\zkpl9e1\Downloads\Program")  '"\")

' The taskDefinition variable is the TaskDefinition object.
Dim taskDefinition
' The flags parameter is 0 because it is not supported.
Set taskDefinition = service.NewTask(0) 

'********************************************************
' Define information about the task.

' RegistrationInfo object
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa382100(v=vs.85).aspx

' Set the registration info for the task by 
' creating the RegistrationInfo object.
Dim regInfo
Set regInfo = taskDefinition.RegistrationInfo
regInfo.Description = "Start Notepad weekly."
regInfo.Author = "Administrator"

' Set the task setting info for the Task Scheduler by
' creating a TaskSettings object.
Dim settings
Set settings = taskDefinition.Settings
settings.Enabled = True
settings.StartWhenAvailable = True
settings.Hidden = False

'********************************************************
' Create a weekly trigger. Note that the start boundary 
' specifies the time of day that the task starts, the 
' day-of-week specfies on what day of the week the task 
' runs, and the interval specifies what weeks the task runs.
Dim triggers
Set triggers = taskDefinition.Triggers

Dim trigger
Set trigger = triggers.Create(TriggerTypeWeekly)

' Trigger variables that define when the trigger is active 
' and the time of day that the task is run. The format of 
' this tims is YYYY-MM-DDTHH:MM:SS
Dim startTime, endTime

Dim time
startTime = "2006-05-02T08:00:00"  'Task runs at 8:00 AM
endTime = "2015-05-02T08:00:00"

Out "startTime :" & startTime
Out "endTime :" & endTime

trigger.StartBoundary = startTime
trigger.EndBoundary = endTime
trigger.DaysOfWeek = 1
trigger.WeeksInterval = 1    'Task runs every week.
trigger.Id = "WeeklyTriggerId"
trigger.Enabled = True

'***********************************************************
' Create the action for the task to execute.

' Add an action to the task to run notepad.exe.
Dim Action
Set Action = taskDefinition.Actions.Create( ActionTypeExec )
Action.Path = "C:\Windows\System32\notepad.exe"

Out "Task definition created. About to submit the task..."

'***********************************************************
' Register (create) the task.

call rootFolder.RegisterTaskDefinition(taskName, taskDefinition, 6, , , 3)

Out "Task submitted."

End Function

ScheduleTaskWin7 "testing"