This article is the result of a quest to better understand Task Scheduler 2.0 and all the newer objects available in vbscript in this version over the limited options we had scripting in Task Scheduler 1.0. As I started my journey of knowledge I found some decent references for the objects on msdn, but could not find very many good sample scripts. There were bits and pieces that told me how to do a few things, but a full picture was not readily available. I decide to build my own full sample script so that I could reference it in the future. I started by just building a script to return all the data from already scheduled tasks (see my article at
本文是通过更好地了解Task Scheduler 2.0和该版本vbscript中可用的所有较新对象(而不是我们在Task Scheduler 1.0中编写脚本的有限选项)的结果。 当我开始知识之旅时,我在msdn上找到了一些有关对象的不错的引用,但是找不到很多好的示例脚本。 有些零零碎碎的东西告诉我如何做一些事情,但是尚无法获得完整的图片。 我决定构建自己的完整示例脚本,以便将来引用。 我首先构建一个脚本以返回已调度任务中的所有数据(请参阅我的文章,网址为
http://rdsrc.us/vVxA6N for that script). My next task was to build a script that could create all the options available for a new task. I found that objects available actually presented more options for creating a task than one even has using the GUI. These objects are pretty powerful and nice to use. As a programmer, I found I had way more options than in task scheduler 1.0 and could do numerous items. There were a couple objects that appear they are only available for the new C++ interface and therefore I have left those out. http://rdsrc.us/vVxA6N )。 我的下一个任务是构建一个脚本,该脚本可以创建用于新任务的所有选项。 我发现可用的对象实际上提供了比使用GUI甚至更多的选项来创建任务。 这些对象功能强大且易于使用。 作为一名程序员,我发现我有比任务计划程序1.0更多的选择,并且可以完成许多工作。 出现了几个对象,它们仅适用于新的C ++接口,因此我将其省略。Below is my script that will set up a task with all the different trigger options and all the different action options. You can take this script and remove the pieces you don't need to create you own script to schedule your task. I have put links to the msdn references in the comments of the code where appropriate.
下面是我的脚本,它将使用所有不同的触发选项和所有不同的操作选项来设置任务。 您可以使用此脚本并删除创建计划脚本所需的片段。 我在适当的地方在代码的注释中放置了指向msdn引用的链接。
Please note that some options will require the script to be run in an elevated mode. As Task Scheduler 2.0 was introduced with Vista, this script will only work on new operating systems like Windows 7 and Windows Server 2008.
请注意,某些选项将要求脚本以提升模式运行。 随着Vista中引入了Task Scheduler 2.0,该脚本仅适用于Windows 7和Windows Server 2008等新操作系统。
'---------------------------------------------------------
' This sample shows how to set the various task objects
' for creating a new scheduled task in Task Scheduler 2.0
'
' An alternative would be to to build the XML and create the t
' task with the .RegisterTask method
' - See http://msdn.microsoft.com/en-us/library/windows/desktop/aa382575%28v=vs.85%29.aspx
'---------------------------------------------------------
' -------------------------------------------------------------------------------
' Define the Available Enumerations that can be used
' Since VBScript does not offer enumeration, we have to set these all as constants
' For all enumeration documentation see - http://msdn.microsoft.com/en-us/library/windows/desktop/aa383602%28v=vs.85%29.aspx
Option Explicit
' TASK_ACTION_TYPE
Const TASK_ACTION_EXEC = 0
Const TASK_ACTION_COM_HANDLER = 5
Const TASK_ACTION_SEND_EMAIL = 6
Const TASK_ACTION_SHOW_MESSAGE = 7
' TASK_COMPATIBILITY
Const TASK_COMPATIBILITY_AT = 0
Const TASK_COMPATIBILITY_V1 = 1
Const TASK_COMPATIBILITY_V2 = 2
' TASK_CREATION
Const TASK_VALIDATE_ONLY = &H01&
Const TASK_CREATE = &H02&
Const TASK_UPDATE = &H04&
Const TASK_CREATE_OR_UPDATE = &H06&
Const TASK_DISABLE = &H08&
Const TASK_DONT_ADD_PRINCIPAL_ACE = &H10&
Const TASK_IGNORE_REGISTRATION_TRIGGERS = &H20&
' TASK_INSTANCES_POLICY
Const TASK_INSTANCES_PARALLEL = 0
Const TASK_INSTANCES_QUEUE = 1
Const TASK_INSTANCES_IGNORE_NEW = 2
Const TASK_INSTANCES_STOP_EXISTING = 3
' TASK_LOGON_TYPE
Const TASK_LOGON_NONE = 0
Const TASK_LOGON_PASSWORD = 1
Const TASK_LOGON_S4U = 2
Const TASK_LOGON_INTERACTIVE_TOKEN = 3
Const TASK_LOGON_GROUP = 4
Const TASK_LOGON_SERVICE_ACCOUNT = 5
Const TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD = 6
' TASK_RUNLEVEL_TYPE
Const TASK_RUNLEVEL_LUA = 0
Const TASK_RUNLEVEL_HIGHEST = 1
' TASK_TRIGGER_TYPE2
Const TASK_TRIGGER_EVENT = 0
Const TASK_TRIGGER_TIME = 1
Const TASK_TRIGGER_DAILY = 2
Const TASK_TRIGGER_WEEKLY = 3
Const TASK_TRIGGER_MONTHLY = 4
Const TASK_TRIGGER_MONTHLYDOW = 5
Const TASK_TRIGGER_IDLE = 6
Const TASK_TRIGGER_REGISTRATION = 7
Const TASK_TRIGGER_BOOT = 8
Const TASK_TRIGGER_LOGON = 9
Const TASK_TRIGGER_SESSION_STATE_CHANGE = 11
' -------------------------------------------------------------------------------
Dim objTaskService, objRootFolder, objTaskFolder, objNewTaskDefinition
Dim objTaskTrigger, objTaskAction, objTaskTriggers, blnFoundTask
Dim objTaskFolders
' Create the TaskService object and connect
Set objTaskService = CreateObject("Schedule.Service")
call objTaskService.Connect()
' Get the Root Folder where we will place this task
Set objTaskFolder = objTaskService.GetFolder("\")
' Or create a folder and use it. I would first check if it exists.
' If it does exist CreateFolder will generate an error.
' You have to loop through the folders to find the one you want
Set objRootFolder = objTaskService.GetFolder("\")
' Get all the sub folders and see if the one one want exists
Set objTaskFolders = objRootFolder.GetFolders(0)
For Each objTaskFolder In objTaskFolders
If objTaskFolder.Path = "\MyNewTaskFolder" Then
blnFoundTask = True
Exit For
End If
Next
If Not blnFoundTask Then Set objTaskFolder = objRootFolder.CreateFolder("\MyNewTaskFolder")
' -------------------------------------------------------------------------------
' Start Creation of the Task Definition
' -------------------------------------------------------------------------------
' The flags parameter is 0 because it is not used and reserved for future use
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa383470%28v=vs.85%29.aspx
Set objNewTaskDefinition = objTaskService.NewTask(0)
With objNewTaskDefinition
' Text that is associated with the task. This data is ignored by the Task Scheduler
' service, but is used by third-parties who wish to extend the task format.
.Data = "This is my sample task via script"
' -------------------------------------------------------------------------------
' Set the values for the registration information - General Tab Top Section
' -------------------------------------------------------------------------------
'http://msdn.microsoft.com/en-us/library/windows/desktop/aa382100%28v=vs.85%29.aspx
With .RegistrationInfo
.Author = "Name or Process Creating Task"
' or
' .Author = objTaskService.ConnectedDomain & "\" & objTaskService.ConnectedUser
.Date = ConvertTime(now())
.Description = "Description of What this task does"
.Documentation = "My Document" ' See - http://msdn.microsoft.com/en-us/library/windows/desktop/aa382104%28v=vs.85%29.aspx
' .SecurityDescriptor ' http://msdn.microsoft.com/en-us/library/windows/desktop/aa379567%28v=vs.85%29.aspx
.Source = "VB Script"
.URI = "http://mysite.com" ' Not Shown in GUI
.Version = "1.0" ' Self defined version of this scheduled task. Not Shown in GUI
End With 'objRegistrationInfo
' -------------------------------------------------------------------------------
' Set the values for the General Tab Security Section
' -------------------------------------------------------------------------------
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa382071%28v=vs.85%29.aspx
With .Principal
.Id = "My ID" ' Not shown in GUI
.DisplayName = "Principal Description" ' Not Shown in GUI
.UserId = "Domain\myuser" ' This script must be run with elevated privileges if this is not the current user.
' or
.UserId = objTaskService.ConnectedDomain & "\" & objTaskService.ConnectedUser
'.GroupId = "" ' The identifier of the user group that is associated with this principal. Do not set this property if a user identifier is specified in the UserId property.
.LogonType = TASK_LOGON_INTERACTIVE_TOKEN ' TASK_LOGON_TYPE
.RunLevel = TASK_RUNLEVEL_LUA ' TASK_RUNLEVEL_TYPE - If you use Highest Privilege, the script will need to run elevated.
End With 'objPrincipal
' -------------------------------------------------------------------------------
' Set Triggers Tab - Examples of the different Types of Triggers
' -------------------------------------------------------------------------------
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa383868%28v=vs.85%29.aspx
Set objTaskTriggers = .Triggers
' *** Event Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa446882%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_EVENT)
With objTaskTrigger
.Enabled = True
.Id = "EventTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
.Delay = "PT5M"
' Need to build Event Subscription XML. This xml can
' be very complicated and I could not find documentation
' I recommend you set up a task with a custom event trigger
' On the custom trigger screen click on the XML tab and copy
' that xml document here to create your trigger. Change all the
' qoute marks (") to single tick marks (') in the copied xml
.Subscription = "<QueryList>" _
& "<Query Id='0' Path='MyTest'>" _
& "<Select Path='Application'>*[System[Provider[@Name='FedExAdminService'] and (Level=1 or Level=2 or Level=3 or Level=4 or Level=0 or Level=5)]]</Select>" _
& "</Query>" _
& "</QueryList>"
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** Time Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa383622%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_TIME)
With objTaskTrigger
.Enabled = True
.Id = "TimeTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** Daily Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa446858%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_DAILY)
With objTaskTrigger
.Enabled = True
.Id = "DailyTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
.DaysInterval = 3 ' Recur every x number of days
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** Weekly Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa384019%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_WEEKLY)
With objTaskTrigger
.Enabled = True
.Id = "WeeklyTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
' Days of Week is a Bit Flag. http://msdn.microsoft.com/en-us/library/windows/desktop/aa384024%28v=vs.85%29.aspx
' Options:
' 1 = Sunday
' 2 = Monday
' 4 = Tuesday
' 8 = Wednesday
' 16 = Thursday
' 32 = Friday
' 64 = Saturday
.DaysOfWeek = 28 ' 28 = Tuesday, Wednesday & Thursday
.WeeksInterval = 2 ' Recur every x number of weeks
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** Monthly Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa382062%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_MONTHLY)
With objTaskTrigger
.Enabled = True
.Id = "MonthlyTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
' Days of Month is a bit Flag -- http://msdn.microsoft.com/en-us/library/windows/desktop/aa382063%28v=vs.85%29.aspx
' Day 1 = &H01&, 2 = &H02&, 3 = &H04&, . . . . 31 = &H40000000&
.DaysOfMonth = &h01& + &h04& + &h40& + &H40000000& ' 1st day, 3rd day, 7th day and 31st Day
.RunOnLastDayOfMonth = True ' Flag for if this should run on the last day of the scheduled months
' Months of the year is a bit flag -- http://msdn.microsoft.com/en-us/library/windows/desktop/aa382064%28v=vs.85%29.aspx
' January = 1, February = 2, March = 4, April = 8, May = 16, June = 32, July = 64, August = 128
' September = 256, October = 512, November = 1024, December = 2048
.MonthsOfYear = 1045 ' January, March, May, November
' Randomly delay the start of the task
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.RandomDelay = "PT4H" ' Randomly Delay for 4 Hours
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** Monthly Day of Week Trigger *** ---
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_MONTHLYDOW)
With objTaskTrigger
.Enabled = True
.Id = "Monthly DayOfMonth TriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
' Days of Week is a Bit Flag. http://msdn.microsoft.com/en-us/library/windows/desktop/aa384024%28v=vs.85%29.aspx
' Options:
' 1 = Sunday
' 2 = Monday
' 4 = Tuesday
' 8 = Wednesday
' 16 = Thursday
' 32 = Friday
' 64 = Saturday
.DaysOfWeek = 28 ' 28 = Tuesday, Wednesday & Thursday
' Weeks of The Month is a bit flag. http://msdn.microsoft.com/en-us/library/windows/desktop/aa382061%28v=vs.85%29.aspx
' First Week = 1, Second Week = 2, Third Week = 4, Fourth Week = 8
.WeeksOfMonth = 9 ' Run on 1st and 4th weeks of month
.RunOnLastWeekOfMonth = True
' Months of the year is a bit flag -- http://msdn.microsoft.com/en-us/library/windows/desktop/aa382064%28v=vs.85%29.aspx
' January = 1, February = 2, March = 4, April = 8, May = 16, June = 32, July = 64, August = 128
' September = 256, October = 512, November = 1024, December = 2048
.MonthsOfYear = 1045 ' January, March, May, November
' Randomly delay the start of the task
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.RandomDelay = "PT4H" ' Randomly Delay for 4 Hours
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** On Idle Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa380690%28v=vs.85%29.aspx
' Make sure the IDLE Properties are also set for this trigger to work.
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_IDLE)
With objTaskTrigger
.Enabled = True
.Id = "OnIdlleTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** On Task Creation/Modification *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa382110%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_REGISTRATION)
With objTaskTrigger
.Enabled = True
.Id = "TaskCreateTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
.Delay = "PT45M"
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** AT Start Up (Boot) Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa446815%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_BOOT)
With objTaskTrigger
.Enabled = True
.Id = "BootTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
.Delay = "PT45M"
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** At Log on Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa381908%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_LOGON)
With objTaskTrigger
.Enabled = True
.Id = "LogonTriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
.Delay = "PT45M"
' For User ID - comment out to leave for any user.
' This script must be run with elevated privileges if this is not the current user or if not used!
.UserId = "Domain\myuser"
' or
.UserId = objTaskService.ConnectedDomain & "\" & objTaskService.ConnectedUser
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
End With
' *** Session State Change Trigger *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa382142%28v=vs.85%29.aspx
Set objTaskTrigger = objTaskTriggers.Create(TASK_TRIGGER_SESSION_STATE_CHANGE)
With objTaskTrigger
.Enabled = True
.Id = "Session State Changed TriggerID1"
' Time Format YYYY-MM-DDTHH:MM:SS or use ConvertTime Format
'.StartBoundary = "2013-07-01T08:08:00"
'.EndBoundary = "2013-07-01T08:08:00"
.StartBoundary = ConvertTime(DateAdd("h", 1, now()))
.EndBoundary = ConvertTime(DateAdd("h", 3, now()))
' Stop Task if it runs longer than . .
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.ExecutionTimeLimit = "PT1M"
.Delay = "PT45M"
' For User ID - comment out to leave for any user.
' This script must be run with elevated privileges if this is not the current user or if not used!
.UserId = "Domain\myuser"
' or
.UserId = objTaskService.ConnectedDomain & "\" & objTaskService.ConnectedUser
' State Change Event - http://msdn.microsoft.com/en-us/library/windows/desktop/aa382144%28v=vs.85%29.aspx
' User Session Connect to Local Computer = 1
' User Session Disconnect from Local Computer = 2
' User Session Connect to Remote Computer = 3
' User Session Disconnect from Remote Computer = 4
' On Workstation Lock = 7
' On Workstation Unlock = 8
.StateChange = 7
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "PT1H"
.Interval = "PT1M"
.StopAtDurationEnd = False
End With 'objTaskRepitition
End With
' -------------------------------------------------------------------------------
' Set Value for Actions Tab - Examples of the different types of actions
' -------------------------------------------------------------------------------
' *** Execute / Command Line Action *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa446890%28v=vs.85%29.aspx
Set objTaskAction = .Actions.Create(TASK_ACTION_EXEC)
With objTaskAction
.Id = "ExecuteAction Sample"
' File Path and Name to run or command line to execute
.Path = "C:\Windows\System32\notepad.exe"
.Arguments = WScript.ScriptFullName
.WorkingDirectory = "C:\Windows\System32"
End With
' *** Email Message Action *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa446868%28v=vs.85%29.aspx
Set objTaskAction = .Actions.Create(TASK_ACTION_SEND_EMAIL)
With objTaskAction
.Id = "Email Message Sample"
.From = "sender.email@abc.com"
.ReplyTo = "replyto.email@abc.com"
.To = "recipient.email@abc.com"
.Cc = "ReceiveCopy.email@abc.com"
.Bcc = "ReceiveBlindCopy.email@abc.com"
.subject = "Test Email from Task Scheduler"
.Body = "All the Text that you want to have in the email."
.Server = "SMTP_Server _Name"
Dim objAttachments(1) ' Array of Attachments - Zero Based
objAttachments(0) = WScript.ScriptFullName
objAttachments(1) = "C:\Windows\Win.ini"
.Attachments = objAttachments
' Create a custom Header Field and value for your email.
' I could not get this to work. It stores in the XML properly
' but task scheduler cannot open it and I had to manually delete from
' the tasks folder in System32
'Dim objHeaderPair
'objHeaderPair = .HeaderFields.Create
'objHeaderPair.Name = "TestHeaderName"
'objHeaderPair.Value = "TestHeaderValue"
'.HeaderFields = objHeaderPair
End With
' *** Show a Message Box Action *** --- http://msdn.microsoft.com/en-us/library/windows/desktop/aa382149%28v=vs.85%29.aspx
Set objTaskAction = .Actions.Create(TASK_ACTION_SHOW_MESSAGE)
With objTaskAction
.Id = "Show a Message Sample"
.Title = "Title for Message Box"
.MessageBody = "Text in the Message Box"
End With
' -------------------------------------------------------------------------------
' Set Values for Conditions and Settings Tabs
' -------------------------------------------------------------------------------
'http://msdn.microsoft.com/en-us/library/windows/desktop/aa383480%28v=vs.85%29.aspx
With .Settings
.Enabled = True ' Must be set to two or task will have a status of disabled
' Compatibility. A Value of 0 or 1 will greatly restrict what objects can be used.
' it is recommended that you user a 2 or 3 with this script
' This value is not required and may be omitted
' 0 = Compatible with AT Command
' 1 = Compatible with Task Scheduler 1.0
' 2 = Compatible with Task Scheduler 2.0 (Windows Vista / Windows 2008)
' 3 = Compatible with Task Scheduler 2.0 (Windows 7 / Windows 2008 R2) - this is not listed in the documentation
.Compatibility = 2
' Optional to Set Priority Level. Can be omitted (recommended)
' 0 = High / 10 = Low. Setting not visible in GUI
.Priority = 5
' -------------------------------------------------------------------------------
' General Tab
' -------------------------------------------------------------------------------
.Hidden = False ' If you mark this as hidden then you must have View >> Show Hidden Tasks enabled to see it
' -------------------------------------------------------------------------------
' Conditions Tab
' -------------------------------------------------------------------------------
' Idle Section
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.RunOnlyIfIdle = True ' Run this task only if the computer has been idle for selected period of time
'http://msdn.microsoft.com/en-us/library/windows/desktop/aa380669%28v=vs.85%29.aspx
With .IdleSettings
.IdleDuration = "PT2M" ' Start the task only if computer is idle for selected time
.StopOnIdleEnd = True ' Stop task if computer ceases to be idle
.RestartOnIdle = True ' Restart if the idle state resumes
.WaitTimeout= "PT2H" ' Time to wait for idle
End With 'objIdleSettings
' Power Section
.DisallowStartIfOnBatteries = True ' Start the task only if the computer is on AC Power
.StopIfGoingOnBatteries = True ' Stop if the computer switches to battery power
.WakeToRun = False ' Wake the computer to run this task
' Network Section
.RunOnlyIfNetworkAvailable = False ' Run only if the selected network is available. Must set network settings
'http://msdn.microsoft.com/en-us/library/windows/desktop/aa382067%28v=vs.85%29.aspx
'With .NetworkSettings
' .Id = "{}" ' SSID For Network
' .Name = "MyNetwork" ' Network Name
'End With 'objTaskNetworkSettings
' -------------------------------------------------------------------------------
' Settings Tab
' -------------------------------------------------------------------------------
.AllowDemandStart = True ' Allow the Task to Be Run on Demand
.StartWhenAvailable = True ' Run Task as soon as possible after a scheduled start is missed.
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.RestartInterval = "PT10M" ' If the task fails attempt to restart every x period of Time (Seconds Not Valid for this Object
.RestartCount = 2 ' Attempt to restart x number of times. Must be set if .RestartInterval is set
.ExecutionTimeLimit = "PT1H" ' Stop the task if it runs longer than chosen time
.AllowHardTerminate = False ' If the task does not end when requested, force it to stop
.DeleteExpiredTaskAfter = "P30D" ' Must have at least one trigger with an expiration date to use this field.
' Tell the task how to function if the task is initiated again while it is already running
' 0 = Run a second instance now (Parallel)
' 1 = Put the new instance in line behind the current running instance (Add To Queue)
' 2 = Ignore the new request"
.MultipleInstances = 2
End With 'objTaskSettings
' Alternatively you could create the task by creating the full XML document and assigning it to .xml
'.xml = "<YourProperlyFormatedXMLString/>"
End With ' objNewTaskDefinition
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa382577%28v=vs.85%29.aspx
' Register The Task
' Path = Name of the scheduled task
' Definiition = The Task Definition object set above
' Flags = Task Creation Constants (Bit Flags)
' userId = The user credentials that are used to register the task.
' If present, these credentials take priority over the credentials
' specified in the task definition object pointed to by the definition parameter.
' password = The password for the userId that is used to register the task. When
' the TASK_LOGON_SERVICE_ACCOUNT logon type is used, the password must be an
' empty VARIANT value such as VT_NULL or VT_EMPTY.
' logonType = Task Logon Type Constant
' ssdl = The security descriptor that is associated with the registered task.
Call objTaskFolder.RegisterTaskDefinition( _
"SampleTask From VBscript", objNewTaskDefinition, TASK_CREATE_OR_UPDATE, , , _
TASK_LOGON_INTERACTIVE_TOKEN)
WScript.Echo "Task submitted."
wscript.quit
Function ConvertTime(DateTimeValue)
' Convert a DateTime value to the format needed by
' task scheduler
' YYYY-MM-DDTHH:MM:SS
Dim strTime
strTime = year(DateTimeValue) & "-"
strTime = strTime & Right("0" & Month(DateTimeValue), 2) & "-"
strTime = strTime & Right("0" & Day(DateTimeValue), 2) & "T"
strTime = strTime & Right("0" & Hour(DateTimeValue), 2) & ":"
strTime = strTime & Right("0" & Minute(DateTimeValue), 2) & ":"
strTime = strTime & Right("0" & Day(DateTimeValue), 2)
ConvertTime = strTime
End Function
Now for those who are interested here is a more detailed breakdown of the code.
现在,对于那些对此感兴趣的人,是该代码的更详细细分。
Lines 17-67
17-67行
First I set up all the enumeration values to make it a little more understandable what the code is doing later on. These are not required for smaller snippets of the code, but you would need to adapt the code to use the actual value and not the referenced constant.
首先,我设置了所有枚举值,以使代码稍后可以更容易理解。 对于较小的代码段,这些不是必需的,但是您需要调整代码以使用实际值,而不是引用的常量。
Lines 75 & 76
75和76行
Connect to the Task Scheduler 2.0 Service. You have to run the connect process to actually get access to the task scheduler
连接到Task Scheduler 2.0服务。 您必须运行连接过程才能实际访问任务计划程序
Lines 78-95
78-95行
Connect to the folder in task scheduler where you want this task and the start the creation of the task
连接到任务计划程序中您要此任务的文件夹,然后开始创建任务
This section has a sample on how to connect to an existing folder or to create a folder. If your script is going
本节提供了有关如何连接到现有文件夹或创建文件夹的示例。 如果您的脚本要执行
to create a new folder, I suggest checking to see if it exists first. If you try to create a folder that already exists,
要创建一个新文件夹,建议您先检查一下是否存在。 如果您尝试创建一个已经存在的文件夹,
you will receive an error.
您将收到一个错误。
Lines 113-124
113-124行
Set the Hidden Registration Information. This is only available if you query the tasks via code and helps to identify this task later on.
设置隐藏的注册信息。 仅当您通过代码查询任务并在以后帮助识别此任务时,此选项才可用。
Note that the Date is optional. But if you include it, it has to be in the proper format. This code has a conversion routine (ConvertTime) that takes a date/time object and converts it to a properly formatted string for this object. [Converstion code is lines 638-652]
请注意,日期是可选的。 但是,如果包含它,则必须采用正确的格式。 此代码具有一个转换例程(ConvertTime),该例程接受一个日期/时间对象,并将其转换为该对象的正确格式的字符串。 [会话代码是第638-652行]
Lines 126-139
126-139行
Set the Values for the General Tab - Security Section. This helps determine what privileges this task will have and who can run the task.
设置“常规”选项卡“安全性”部分的值。 这有助于确定此任务将具有哪些特权以及谁可以运行该任务。
'-------------------------
'------------------------- ---
Lines 141-490
141-490行
Set what type of events or situations, which are know as triggers, will cause the task to start. There are several options and a scheduled task can have more than one trigger and these are shown on the Triggers tab in the GUI. The example code will set several for the same scheduled task.
设置什么类型的事件或情况(称为触发器)将导致任务启动。 有多个选项,一个计划的任务可以有多个触发器,这些都显示在GUI的“触发器”选项卡上。 该示例代码将为同一计划任务设置多个。
'-------------------------
'------------------------- ---
The repetition section for each trigger sets if the task should be repeatedly run for a section of time once the trigger has fired. The .Duration property sets for how long the task should repeatedly run. The .Interval property sets how often the task should fire during that period of time. If .StopAtDurationEnd is set to true, then all running tasks will be stopped when the allotted time set by .Duration has ended.
每个触发器的重复部分设置是否在触发器触发后在一段时间内重复运行任务。 .Duration属性设置任务应重复运行多长时间。 .Interval属性设置在该时间段内任务应多久触发一次。 如果.StopAtDurationEnd设置为true,则当.Duration设置的分配时间结束时,所有正在运行的任务将停止。
With .Repetition
' Format For Days = P#D where # is the number of days
' Format for Time = PT#[HMS] Where # is the duration and H for hours, M for minutes, S for seconds
.Duration = "P1D"
.Interval = "PT1H"
.StopAtDurationEnd = True
End With 'objTaskRepitition
Lines 146-181
线146-181
Event Trigger: There are several logged Windows Events that can fire a task. I suggest looking at all the options in the GUI to determine which scenarios fit. Also, the settings for this event are a little tricky. If you create a sample task in the GUI, you can copy the settings very easily into the code. On the Triggers Tab in the GUI, click New. Then select "On an Event" in the Begin Task Drop Down. In the settings box, select custom and click the New Event Filter Button. Set up the event options and then click on the XML tab. Copy that text and use it to the build the .subscription string.
事件触发器:有多个可以触发任务的已记录Windows事件。 我建议查看GUI中的所有选项以确定适合的方案。 另外,此事件的设置有些棘手。 如果在GUI中创建示例任务,则可以非常轻松地将设置复制到代码中。 在GUI的“触发器”选项卡上,单击“新建”。 然后在“开始任务”下拉列表中选择“事件时”。 在设置框中,选择“自定义”,然后单击“新建事件筛选器”按钮。 设置事件选项,然后单击XML选项卡。 复制该文本并将其用于构建.subscription字符串。
Lines 183-205
183-205行
Time Trigger: This is a one-time trigger that fires based on the set time and day. It will initiate just once and will repeat until the end of repeat stamp if repitition is set.
时间触发器:这是一次触发,会根据设置的时间和日期触发。 如果设置了重填位,它将仅启动一次并重复直到重复印记结束。
Lines 207-230
207-230行
Daily Trigger: This will set to run at a certain time each day. You can set a start and end date for a period of consecutive days in which this task will run each day. You can set an interval (.DaysInterval) where the task will be run every X number of days instead of daily. This daily task can also start a repetition pattern - for example, you want to script to run every 30 minutes from 9 a.m. until 9 p.m.
每日触发:将设置为每天的特定时间运行。 您可以将连续一天的开始和结束日期设置为每天执行此任务的时间。 您可以设置一个间隔(.DaysInterval),任务将每X天而不是每天运行一次。 此日常任务还可以启动重复模式-例如,您希望编写脚本以使其从上午9点到晚上9点每30分钟运行一次
Line 232-265
232-265行
Weekly Trigger: This will set up a a task to run each week on certain days of the week (Sunday - Saturday). You can set it to occur every so many weeks - for example every other week.
每周触发:这将设置一个任务,使其在每周的某些天(星期日-星期六)运行。 您可以将其设置为每隔几周发生一次,例如每隔一周一次。
Lines 267-347
267-347行
Monthly Triggers: There are two different monthly type triggers. One will let you pick which day of the week on which the task is run and the other lets you pick on which day of the month it should run (you can even choose if it should run on the last day of each month). This gives you many options on how to schedule your task.
每月触发器:有两种不同的每月类型触发器。 一个可以让您选择要在一周中的哪一天运行任务,而另一个可以让您选择应在每月的哪一天运行(您甚至可以选择是否应在每月的最后一天运行)。 这为您提供了许多有关如何安排任务的选项。
Lines 349-372
线349-372
PC Idle Time Triggers: This code will set a trigger to run the scheduled task for when the computer has been idle. Set the length of time the pc must be idle in the "Conditions and Settings" section later in the code.
PC空闲时间触发器:此代码将设置触发器,以在计算机空闲时运行计划的任务。 在代码后面的“条件和设置”部分中设置计算机必须空闲的时间长度。
Lines 232-265
232-265行
Weekly Trigger: This trigger will select the specific days in the week for the task to run. You can select the weekly pattern also such as run every other week.
每周触发器:此触发器将选择一周中要运行任务的特定日期。 您还可以选择每周模式,例如每隔一周运行一次。
Lines 267-347
267-347行
Monthly Triggers: You can choose in which months the task should run. You can set this either by the day of the month (1st, 2nd, 3rd, etc.) or by choosing a day of the week and which weeks in the month this task should run. You can also set it to always run on the last day of the month which will adjust to the number of days in a month automatically. Note that the .DaysOfMonth value is a bit flag. However vbscript cannot pass a decimal bit value to this parameter as it will error from an overflow. With this flag you need to set you values using the Hexadecimal codes such as &h01& for the first day of the month.
每月触发器:您可以选择任务应在哪个月运行。 您可以在每月的某天(第一天,第二天,第三天等)进行设置,也可以选择一周中的某一天以及该任务应在每月的哪几周进行设置。 您还可以将其设置为始终在每月的最后一天运行,这会自动调整为一个月中的天数。 请注意,.DaysOfMonth值是一个位标志。 但是,vbscript无法将十进制值传递给此参数,因为它将因溢出而出错。 使用此标志,您需要在每月的第一天使用十六进制代码(例如&h01&)设置值。
Lines 249-372
249-372行
PC Idle Triggers: This trigger will start when the machine has been idle for the set amount of time. Please note that you will need to set the IDLE Properties also for this trigger. (Lines 567-577)
PC闲置触发器:当机器闲置了设定的时间后,此触发器将启动。 请注意,您还需要为此触发器设置IDLE属性。 (第567-577行)
Lines 374-397
线374-397
Upon Task Creation or Modification: This will mark the task to run if something changes with the task
创建或修改任务时:如果任务发生更改,这将标记任务运行
Lines 399-422
399-422行
Start Up Trigger: Set the task to run when the machine has started up or has rebooted
启动触发器:将任务设置为在计算机启动或重新启动时运行
Lines 424-452
424-452行
Log On Trigger: Run the task whenever a user logs on to the machine. If you leave the user name and password options blank it will run for every user or you can set it to run only when a certain user logs on.
登录触发器:每当用户登录到计算机时,运行任务。 如果将用户名和密码选项留为空白,它将对每个用户运行,或者可以将其设置为仅在特定用户登录时运行。
Lines 454-490
线454-490
Session State Change: You can set the task to run when certain OS type events happen. These are mainly focused around remote connection or workstation lock events.
会话状态更改:您可以将任务设置为在发生某些OS类型事件时运行。 这些主要集中于远程连接或工作站锁定事件。
'-------------------------
'------------------------- ---
Lines 495-539
495-539行
The next section covers what the task should do when the trigger is fired.
下一部分将介绍触发触发器时任务应执行的操作。
'-------------------------
'------------------------- ---
Lines 495-503
495-503行
Execute: This will run some type of executable program like a .exe, .bat, .vbs, etc type file. You can also pass parameters to the file to be run.
执行:这将运行某种类型的可执行程序,例如.exe,.bat,.vbs等类型的文件。 您还可以将参数传递给要运行的文件。
Lines 505-531
505-531行
Email: This will attempt to send an email using the SMTP Server settings that are set on the task.
电子邮件:这将尝试使用在任务上设置的SMTP服务器设置发送电子邮件。
Lines 533-539
533-539行
Message Box: This will display a message box to the user
消息框:这将向用户显示一个消息框
'-------------------------
'------------------------- ---
Lines 541-614
541-614行
The next section covers how to modify the values for the Conditions and for the settings tabs in the GUI
下一节将介绍如何在GUI中修改“条件”和“设置”选项卡的值
'-------------------------
'------------------------- ---
Here you set the task to enabled so that it will run on the set time (trigger). You can set some other values for how long can the task run and what to do with power saving settings.
在这里,您将任务设置为启用,以便它将在设置的时间运行(触发)。 您可以为任务可以运行多长时间以及如何进行节能设置设置其他一些值。
Now we can save the task.
现在我们可以保存任务。
The last section is just a function to covert a Date value to the format needed by the task scheduler.
最后一部分只是将Date值转换为任务计划程序所需格式的函数。