VBScript for creating a scheduled task
Asked Answered
S

3

6

I'm trying to create a VBScript that creates a batch file then creates a scheduled task to run the batch file. So far everything I've tried creates the batch file, but does not create the scheduled task and I haven't received any errors. Here is what I have so far:

Option Explicit

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

Set outFile = objFSO.CreateTextFile("C:\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:\test.bat' /ST 16:30", 0

I've tried ""Test Task"" and ""C:\test.bat"", and got the same results. But when I run the following command at the command prompt:

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

The task gets created successfully.

Another way I tried this was to create 2 batch files: one batch file to open the webpage, and one batch file to create the scheduled task. Then I concluded with running the task.bat file at the end. Here's what I had for this:

Option Explicit

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

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

Set outFile = objFSO.CreateTextFile("C:\task.bat", True)
outFile.WriteLine "SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN ""Test Task"" /TR ""C:\test.bat"" /ST 16:30"

Set wShell = CreateObject ("Wscript.Shell") 
wShell.Run "cmd start ""C:\task.bat"""

This created the batch files but just opened cmd at the end and did nothing after that.

My guess is that the problem lies in the wShell.Run portion, but I'm not experienced enough to know where the problem lies.

I'm not sure where to go from here so any suggestions would be great.

Sorkin answered 21/7, 2015 at 20:52 Comment(0)
T
5

There's no need for cmd. Schtasks is its own executable, not a command within cmd. And for your quoted params, just use two quotes.

For example:

wShell.Run "SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN ""Test Task"" /TR ""C:\test.bat"" /ST 16:30", 0
Transilient answered 21/7, 2015 at 20:59 Comment(1)
Beware, though, that schtasks does not provide all options the GUI does. The Schedule.Service object allows more complete control over task properties.Remission
B
7

As a VBScript you can do anything a command can do.

Here's how to list scheduled tasks in the root folder.

Set TS = CreateObject("Schedule.Service")
TS.Connect("Serenity")

Set rootFolder = TS.GetFolder("\")

Set tasks = rootFolder.GetTasks(0)

If tasks.Count = 0 Then 
    Wscript.Echo "No tasks are registered."
Else
    WScript.Echo "Number of tasks registered: " & tasks.Count

    For Each Task In Tasks
    A=Task.Name
    A = A & " " & Task.NextRunTime
    A = A & " " & Task.LastTaskResult
    wscript.echo A
    Next
End If

This is from the documentation showing how to create a task.

Time Trigger Example (Scripting)

This scripting example shows how to create a task that runs Notepad at a specific time. The task contains a time-based trigger that specifies a start boundary to activate the task, an executable action that runs Notepad, and an end boundary that deactivates the task.

The following procedure describes how to schedule a task to start an executable at a specific time.

To Schedule Notepad to start at a Specific Time

  1. Create a TaskService object. This object allows you to create the task in a specified folder.

  2. Get a task folder and create a task. Use the TaskService.GetFolder method to get the folder where the task is stored and the TaskService.NewTask method to create the TaskDefinition object that represents the task.

  3. Define information about the task using the TaskDefinition object. Use the TaskDefinition.Settings property to define the settings that determine how the Task Scheduler service performs the task and the TaskDefinition.RegistrationInfo property to define the information that describes the task.
  4. Create a time-based trigger using the TaskDefinition.Triggers property. This property provides access to the TriggerCollection object. Use the TriggerCollection.Create method (specifying the type of trigger you want to create) to create a time-based trigger. As you create the trigger, set the start boundary and end boundary of the trigger to activate and deactivate the trigger. The start boundary specifies when the task's action will be performed.
  5. Create an action for the task to execute by using the TaskDefinition.Actions property. This property provides access to the ActionCollection object. Use the ActionCollection.Create method to specify the type of action you want to create. This example uses an ExecAction object, which represents an action that executes a command-line operation.
  6. Register the task using the TaskFolder.RegisterTaskDefinition method. For this example the task will start Notepad at the current time plus 30 seconds.

The following VBScript example shows how to schedule a task to execute Notepad 30 seconds after the task is registered.

' This sample schedules a task to start notepad.exe 30 seconds
' from the time the task is registered.
'------------------------------------------------------------------

' A constant that specifies a time-based trigger.
const TriggerTypeTime = 1
' A constant that specifies an executable action.
const ActionTypeExec = 0   

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

'********************************************************
' Get a folder to create a task definition in. 
Dim rootFolder
Set rootFolder = service.GetFolder("\")

' 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.

' Set the registration info for the task by 
' creating the RegistrationInfo object.
Dim regInfo
Set regInfo = taskDefinition.RegistrationInfo
regInfo.Description = "Start notepad at a certain time"
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 time-based trigger.
Dim triggers
Set triggers = taskDefinition.Triggers

Dim trigger
Set trigger = triggers.Create(TriggerTypeTime)

' Trigger variables that define when the trigger is active.
Dim startTime, endTime

Dim time
time = DateAdd("s", 30, Now)  'start time = 30 seconds from now
startTime = XmlTime(time)

time = DateAdd("n", 5, Now) 'end time = 5 minutes from now
endTime = XmlTime(time)

WScript.Echo "startTime :" & startTime
WScript.Echo "endTime :" & endTime

trigger.StartBoundary = startTime
trigger.EndBoundary = endTime
trigger.ExecutionTimeLimit = "PT5M"    'Five minutes
trigger.Id = "TimeTriggerId"
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"

WScript.Echo "Task definition created. About to submit the task..."

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

call rootFolder.RegisterTaskDefinition( _
    "Test TimeTrigger", taskDefinition, 6, , , 3)

WScript.Echo "Task submitted."

'------------------------------------------------------------------
' Used to get the time for the trigger 
' startBoundary and endBoundary.
' Return the time in the correct format: 
' YYYY-MM-DDTHH:MM:SS. 
'------------------------------------------------------------------
Function XmlTime(t)
    Dim cSecond, cMinute, CHour, cDay, cMonth, cYear
    Dim tTime, tDate

    cSecond = "0" & Second(t)
    cMinute = "0" & Minute(t)
    cHour = "0" & Hour(t)
    cDay = "0" & Day(t)
    cMonth = "0" & Month(t)
    cYear = Year(t)

    tTime = Right(cHour, 2) & ":" & Right(cMinute, 2) & _
        ":" & Right(cSecond, 2)
    tDate = cYear & "-" & Right(cMonth, 2) & "-" & Right(cDay, 2)
    XmlTime = tDate & "T" & tTime 
End Function
Barrelchested answered 21/7, 2015 at 21:52 Comment(3)
Please do not quote external sources without reference.Remission
I said From help. It's not my fault you won't use it. Also note the build date that specifies exactly which edition of Help it's from. And I posted this thousands of times in the last 9 years - Download and install Windows SDK msdn.microsoft.com/en-us/windows/hardware/hh852363Barrelchested
References to (unspecified) offline documentation are not terribly helpful, particularly when the online documentation is trivial to find.Remission
T
5

There's no need for cmd. Schtasks is its own executable, not a command within cmd. And for your quoted params, just use two quotes.

For example:

wShell.Run "SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN ""Test Task"" /TR ""C:\test.bat"" /ST 16:30", 0
Transilient answered 21/7, 2015 at 20:59 Comment(1)
Beware, though, that schtasks does not provide all options the GUI does. The Schedule.Service object allows more complete control over task properties.Remission
N
1

In the script, you used single quotes in the command, while in your test in CMD, you used double quotes. Does it still work if you run .. ?:

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

If not, try with double quotes and escape them by doubling them:

wShell.Run "SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN ""Test Task"" /TR ""C:\test.bat"" /ST 16:30", 0
Nagel answered 21/7, 2015 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.