Introduction
A brief example of how to create a simple task in Windows Task Scheduler using VB. NET
Background
Tested on Windows 8.
A question in the CodeProject Quick Answers area prompted me to create a test program that shows how to create a task in Task Scheduler.
Specifically, the behavior of the Hidden
attribute was in question. I used this code to determine the cause of the issue. See the comments in the code below to learn about the issue with the Hidden
attribute.
Using the code
Copy the source code and modify to your needs. If you need C#, use one of the free code translators to translate it for you.
Add a Reference to C:\WINDOWS\SYSTEM32\taskschd.dll or C:\WINDOWS\SYSWOW64\taskschd.dll which will create Interop.TaskScheduler.dll.
Imports TaskScheduler
Public Sub CreateSchedule()
Dim taskService As ITaskService = New TaskScheduler.TaskScheduler()
taskService.Connect()
Dim taskDefinition As ITaskDefinition = taskService.NewTask(0)
taskDefinition.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW
taskDefinition.RegistrationInfo.Description = "Testing the creation of a scheduled task via VB .NET"
taskDefinition.Principal.LogonType = _TASK_LOGON_TYPE.TASK_LOGON_GROUP
taskDefinition.Settings.Hidden = False
Dim taskTrigger As IDailyTrigger = _
DirectCast(taskDefinition.Triggers.Create _
(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY), IDailyTrigger)
taskTrigger.StartBoundary = _
DateTime.Now.AddMinutes(10).ToString _
("yyyy-MM-ddThh:mm:ss" & _
TimeZone.CurrentTimeZone.GetUtcOffset(Now).ToString.Substring(0, 6))
taskTrigger.DaysInterval = 2
Dim taskAction As IExecAction = _
DirectCast(taskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC), IExecAction)
taskAction.Path = "C:\windows\notepad.exe"
taskAction.Arguments = ""
taskAction.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Const taskName As String = "Testing creation of a scheduled task"
Dim rootFolder As ITaskFolder = taskService.GetFolder("\")
rootFolder.RegisterTaskDefinition( _
taskName, taskDefinition, _
CInt(_TASK_CREATION.TASK_CREATE_OR_UPDATE), _
"MyUsername", "MyPassword", _
_TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD)
While System.Runtime.InteropServices.Marshal.ReleaseComObject(rootFolder) <> 0
Application.DoEvents()
End While
rootFolder = Nothing
While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskTrigger) <> 0
Application.DoEvents()
End While
taskTrigger = Nothing
While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskAction) <> 0
Application.DoEvents()
End While
taskAction = Nothing
While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskDefinition) <> 0
Application.DoEvents()
End While
taskDefinition = Nothing
While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskService) <> 0
Application.DoEvents()
End While
taskService = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
History
- Version 1 - 14 June 2013.