Quantcast
Channel: Task Scheduler Managed Wrapper
Viewing all 2206 articles
Browse latest View live

New Post: Task Scheduler TaskRunLevel

0
0

It's Windows 7.

The entire code is below:

                using (TaskService ts = new TaskService())
                {
                    // Create a new task definition and assign properties



                    if (schday == "ALL")
                    {

try
                        {
                            string userId = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);


                           
                            TaskDefinition tdall = ts.NewTask();
                            userId = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);
                           
                            tdall.RegistrationInfo.Description = schtask.ToString() + i.ToString();
                            tdall.Principal.LogonType = TaskLogonType.S4U;
                            tdall.Principal.RunLevel = TaskRunLevel.Highest;
                            tdall.Principal.UserId = userId;
                           
                            DailyTrigger dtall = new DailyTrigger();

                            // Add a trigger that will fire the task at this time every day
                            dtall = (DailyTrigger)tdall.Triggers.Add(new DailyTrigger { DaysInterval = 1 });
                            dtall.StartBoundary = schtime;


                            tdall.Actions.Add(new ExecAction("psshutdown.exe", "-d -accepteula", @"C:\EnergyWatchIT\App_Files\"));

                            i++;
                            string taskName = "EWITSchedSleepAll" + schtask.ToString() + i.ToString();

                            

                            ts.RootFolder.RegisterTaskDefinition(taskName, tdall, TaskCreation.CreateOrUpdate, userId, LogonType: TaskLogonType.S4U);



                            
                        }
                        catch (Exception j)
                        {
                            Logger.append("j is  " + j.Message + Environment.NewLine + j.StackTrace, Logger.ALL);
                            MessageBox.Show("j is " + j.ToString());
                        }

try
                        {
                            string userId = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);


                           
                            TaskDefinition tdall = ts.NewTask();
                            userId = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);
                           
                            tdall.RegistrationInfo.Description = schtask.ToString() + i.ToString();
                            tdall.Principal.LogonType = TaskLogonType.S4U;
                            tdall.Principal.RunLevel = TaskRunLevel.Highest;
                            tdall.Principal.UserId = userId;
                           
                            DailyTrigger dtall = new DailyTrigger();

                            // Add a trigger that will fire the task at this time every day
                            dtall = (DailyTrigger)tdall.Triggers.Add(new DailyTrigger { DaysInterval = 1 });
                            dtall.StartBoundary = schtime;


                            tdall.Actions.Add(new ExecAction("psshutdown.exe", "-d -accepteula", @"C:\EnergyWatchIT\App_Files\"));

                            i++;
                            string taskName = "EWITSchedSleepAll" + schtask.ToString() + i.ToString();

                            

                            ts.RootFolder.RegisterTaskDefinition(taskName, tdall, TaskCreation.CreateOrUpdate, userId, LogonType: TaskLogonType.S4U);



                            
                        }
                        catch (Exception j)
                        {
                            Logger.append("j is  " + j.Message + Environment.NewLine + j.StackTrace, Logger.ALL);
                            MessageBox.Show("j is " + j.ToString());
                        }




  static void sleepmethod(String schtask, String schday, DateTime schtime, int i)
        {

            try
            {


                using (TaskService ts = new TaskService())
                {
                    // Create a new task definition and assign properties



                    if (schday == "ALL")
                    {
                        try
                        {
                            string userId = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);


                            MessageBox.Show("In try");
                            TaskDefinition tdall = ts.NewTask();
                            userId = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);
                            MessageBox.Show(userId);
                            tdall.RegistrationInfo.Description = schtask.ToString() + i.ToString();
                            tdall.Principal.LogonType = TaskLogonType.S4U;
                            tdall.Principal.GroupId = "Users";
                            //tdall.Principal.RunLevel = TaskRunLevel.Highest;
                            tdall.Principal.UserId = userId;
                           
                            DailyTrigger dtall = new DailyTrigger();

                            // Add a trigger that will fire the task at this time every day
                            dtall = (DailyTrigger)tdall.Triggers.Add(new DailyTrigger { DaysInterval = 1 });
                            dtall.StartBoundary = schtime;


                            tdall.Actions.Add(new ExecAction("psshutdown.exe", "-d -accepteula", @"C:\EnergyWatchIT\App_Files\"));

                            i++;
                            string taskName = "EWITSchedSleepAll" + schtask.ToString() + i.ToString();



                            ts.RootFolder.RegisterTaskDefinition(taskName, tdall, TaskCreation.CreateOrUpdate, "NETWORK SERVICE", LogonType: TaskLogonType.Group);



                            
                        }
                        catch (Exception j)
                        {
                            Logger.append("j is  " + j.Message + Environment.NewLine + j.StackTrace, Logger.ALL);
                            MessageBox.Show("j is " + j.ToString());
                        }
                    }

}
}

New Post: Reading fields from Actions

0
0

I am trying to get the fields from the Actions of a task, but I'm not finding how to access them.

Here is a small code sample:

Dim Actions As Microsoft.Win32.TaskScheduler.ActionCollection = myTask.Definition.Actions
            For Each act As Microsoft.Win32.TaskScheduler.Action In Actions
                If act.ActionType = Microsoft.Win32.TaskScheduler.TaskActionType.Execute Then
                    Dim args As String = ???

I have an Execute Action, and I want to get the arguments for the execute action, or the path, etc.

On the Email action, I would like to get the from, to, etc.  How do I access those fields.

Thanks

 

New Post: Reading fields from Actions

0
0

Sorry, that was too easy

dim ea as ExecAction = act

Thanks,

Updated Wiki: Home

0
0
Project Description
This project provides a single assembly wrapper for the 1.0 and 2.0 versions of Task Scheduler found in all Microsoft operating systems post Windows 98. It simplifies the coding, aggregates the multiple versions, provides an editor and allows for localization support.

Microsoft introduced version 2.0 (internally version 1.2) with a completely new object model with Windows Vista. The managed assembly closely resembles the new object model, but allows the 1.0 (internally version 1.1) COM objects to be manipulated. It will automatically choose the most recent version of the library found on the host system (up through 1.4). The project was written in C#, but works with any .NET language including scripting languages.

The project is based on work the originator started in January 2002 with the 1.0 library that is currently hosted on CodeProject.

There is a second library that includes a GUI editor and a wizard for tasks which mimic the ones in Vista and later and adds optional pages for new properties. There are also a few UI goodies for you code junkies. There is a DropDownCheckList control that is very useful for selecting flag type enumerations. There is a FullDateTimePicker control which allows both date and time selection in a single control. There is a CredentialsDialog class for prompting for a password which wraps the Windows API. Lastly, there is code that simplifies pulling events from the system event log.

There is a help file included with the download that provides an overview of the various classes. Below is a brief example of how to use the library from C#.

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}
If you really want to squeeze things into a single line of code (without any error handling):

new TaskService().AddTask("Test", new DailyTrigger { DaysInterval = 2 }, new ExecAction("notepad.exe", "c:\\test.log", null));
For extended examples on how to the use the library, look in the source code area or look at the Examples Page. The library closely follows the Task Scheduler 2.0 Scripting classes. Microsoft has some examples on MSDN around it that may further help you understand how to use this library.

Source code checked in, #80785

0
0
* Fixed problem with warnings having title and message strings mixed * Fixed problem with account validation when Principal.ProcessTokenSidType * Hid new tabs by default

Released: Release 1.9 (Oct 29, 2012)

0
0
Many bug fixes, full support for Windows 7 and Windows 8 additions to core library, and an enhanced editor to allow editing of all properties, since the 1.8.3 release. See Source Code for full details of changes.

Download Descriptions
  • TaskScheduler.zip - Includes the base library (Microsoft.Win32.TaskScheduler.dll) with no UI code. Works with .NET 2.0 and higher. Add this assembly as a reference to interact with Task Scheduler on all systems with IE4 and later. This package is also available via NuGet with package name TaskScheduler.
  • TaskSchedulerEditor.zip - Includes the UI library (Microsoft.Win32.TaskSchedulerEditor.dll) with all supporting assemblies. Works with .NET 3.5 and higher. Add this assembly as a reference along with Microsoft.Win32.TaskScheduler.dll to get editor controls and dialogs that allow for viewing and editing tasks, triggers, actions, lists, etc. This package is also available via NuGet with package name TaskSchedulerEditor.
  • TaskSchedulerHelp.zip - Includes the Microsoft Help (VS2010) compatible help files for both the base and editor libraries. Extract all files and then run Install_TaskScheduler.bat to integrate the help.

Updated Release: Release 1.9 (Oct 29, 2012)

0
0
Many bug fixes, full support for Windows 7 and Windows 8 additions to core library, and an enhanced editor to allow editing of all properties, since the 1.8.3 release. See Source Code for full details of changes.

Download Descriptions
  • TaskScheduler.zip - Includes the base library (Microsoft.Win32.TaskScheduler.dll) with no UI code. Works with .NET 2.0 and higher. Add this assembly as a reference to interact with Task Scheduler on all systems with IE4 and later. This package is also available via NuGet with package name TaskScheduler.
  • TaskSchedulerEditor.zip - Includes the UI library (Microsoft.Win32.TaskSchedulerEditor.dll) with all supporting assemblies. Works with .NET 3.5 and higher. Add this assembly as a reference along with Microsoft.Win32.TaskScheduler.dll to get editor controls and dialogs that allow for viewing and editing tasks, triggers, actions, lists, etc. This package is also available via NuGet with package name TaskSchedulerEditor.
  • TaskSchedulerHelp.zip - Includes the Microsoft Help (VS2010) compatible help files for both the base and editor libraries. Extract all files and then run Install_TaskScheduler.bat to integrate the help.

Updated Wiki: Documentation

0
0
There is a help file included with the download that provides an overview of the various classes. The Microsoft MSDN documentation provides an excellent overview of the Task Scheduler along with details around security and permission, idle conditions, and trigger repetition.
  • The Examples Page shows some C# code that demonstrates almost every function of the library.
  • The Installation Page explains how to use this library in your own projects and includes a sample project.
The TaskService class represents the machine specific instance of the system task scheduler. It provides access to information about the service, access folders (2.0 only), and can quickly add or retrieve a task. If you only need to use the library for very intermitant periods, wrap the TaskService instantiation in a using statement to easily disconnect at the end of your use. However, if you plan on using the connection to the Task Scheduler repeatedly, use an assembly level field to store the TaskService instance as connecting and disconnecting is an expensive operation.

Tasks are accessed and can be enumerated through a TaskFolder. For systems supporting only the 1.0 library, there is only the root folder. The 2.0 library supports a hierarchal structure similar to a file system. The Tasks property exposes a TaskCollection instance which can enumerate tasks and provides an indexer which allows access to individual tasks by name. The TaskCollection class also has methods that allow for the creation/registration and deletion of tasks and subfolders by name.

A task is represented by a Task instance. The Task class provides information about tasks state and history and exposes the task's TaskDefinition through the Definition property.

A TaskDefinition exposes all of the properties of a task which allow you to define how and what will run when the task is triggered. A task must have at least one action and one trigger defined.

Each task has a list of triggers that determine when the task will be run. These are accessed through the Triggers property of a task definition which exposes a TriggerCollection instance. TriggerCollection provides an indexer which allows access to individual triggers by their position in the list. The TriggerCollection class also has methods that allow for the addition and removal of triggers. TriggerCollection implements the IList interface so you can also enumerate all tasks using the foreach construct.

The Trigger class is an abstract class that forms the foundation of the different types of triggers that can be specified for a task. There are 10 different specializations that provide different ways to specify the time a task will run. Not all specializations work with the 1.0 library. See the help file for details about each of the trigger classes. The Trigger Documentation has some examples of how to setup each kind of trigger.

The Action class is an abstract class that is the foundation for four different actions. On 1.0, only the ExecAction specialization is available. These actions determine what the service will do when a trigger is fired. The Action Documentation has some examples of how to setup each kind of action.

Below is a brief example of how to use the library from C#.

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}
Here's the same as above but in VB.NET

Imports Microsoft.Win32.TaskScheduler

Module Module1

    Sub Main()
        Using ts As New TaskService()
            ' Create a new task definition and assign properties
            Const taskName As String = "Test"
            Dim td As TaskDefinition = ts.NewTask
            td.RegistrationInfo.Description = "Does something"

            ' Add a trigger that will fire every other week on Monday and Saturday and repeat
            ' every 10 minutes for the following 11 hours
            Dim wt As New WeeklyTrigger()
            wt.DaysOfWeek = DaysOfTheWeek.Monday Or DaysOfTheWeek.Saturday
            wt.WeeksInterval = 2
            wt.StartBoundary = Now
            wt.Repetition.Duration = TimeSpan.FromHours(11)
            wt.Repetition.Interval = TimeSpan.FromMinutes(10)
            td.Triggers.Add(wt)

            ' Add an action (shorthand) that runs Notepad
            td.Actions.Add(New ExecAction("notepad.exe", "C:\Test.log"))

            ' Register the task in the root folder
            ts.RootFolder.RegisterTaskDefinition(taskName, td)

            ' Remove the task we just created
            ts.RootFolder.DeleteTask(taskName)
        End Using
    End Sub

End Module
If you're really into shorthand code, here's almost the same functionality as the C# code above, but much shorter:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      new TaskService().AddTask("Test", new DailyTrigger { DaysInterval = 2 }, new ExecAction("notepad.exe", "c:\\test.log", null));
   }
}

Updated Wiki: Documentation

0
0
There is a help file included with the download that provides an overview of the various classes. The Microsoft MSDN documentation provides an excellent overview of the Task Scheduler along with details around security and permission, idle conditions, and trigger repetition.
  • The Examples Page shows some C# code that demonstrates almost every function of the library.
  • The Installation Page explains how to use this library in your own projects and includes a sample project.
The TaskService class represents the machine specific instance of the system task scheduler. It provides access to information about the service, access folders (2.0 only), and can quickly add or retrieve a task. If you only need to use the library for very intermitant periods, wrap the TaskService instantiation in a using statement to easily disconnect at the end of your use. However, if you plan on using the connection to the Task Scheduler repeatedly, use an assembly level field to store the TaskService instance as connecting and disconnecting is an expensive operation.

Tasks are accessed and can be enumerated through a TaskFolder. For systems supporting only the 1.0 library, there is only the root folder. The 2.0 library supports a hierarchal structure similar to a file system. The Tasks property exposes a TaskCollection instance which can enumerate tasks and provides an indexer which allows access to individual tasks by name. The TaskCollection class also has methods that allow for the creation/registration and deletion of tasks and subfolders by name.

A task is represented by a Task instance. The Task class provides information about tasks state and history and exposes the task's TaskDefinition through the Definition property.

A TaskDefinition exposes all of the properties of a task which allow you to define how and what will run when the task is triggered. A task must have at least one action and one trigger defined.

Each task has a list of triggers that determine when the task will be run. These are accessed through the Triggers property of a task definition which exposes a TriggerCollection instance. TriggerCollection provides an indexer which allows access to individual triggers by their position in the list. The TriggerCollection class also has methods that allow for the addition and removal of triggers. TriggerCollection implements the IList interface so you can also enumerate all tasks using the foreach construct.

The Trigger class is an abstract class that forms the foundation of the different types of triggers that can be specified for a task. There are 10 different specializations that provide different ways to specify the time a task will run. Not all specializations work with the 1.0 library. See the help file for details about each of the trigger classes. The Trigger Documentation has some examples of how to setup each kind of trigger.

The Action class is an abstract class that is the foundation for four different actions. On 1.0, only the ExecAction specialization is available. These actions determine what the service will do when a trigger is fired. The Action Documentation has some examples of how to setup each kind of action.

Below is a brief example of how to use the library from C#.

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}
Here's the same as above but in VB.NET

Imports Microsoft.Win32.TaskScheduler

Module Module1

    Sub Main()
        Using ts As New TaskService()
            ' Create a new task definition and assign properties
            Const taskName As String = "Test"
            Dim td As TaskDefinition = ts.NewTask
            td.RegistrationInfo.Description = "Does something"

            ' Add a trigger that will fire every other week on Monday and Saturday and
            ' repeat every 10 minutes for the following 11 hours
            Dim wt As New WeeklyTrigger()
            wt.DaysOfWeek = DaysOfTheWeek.Monday Or DaysOfTheWeek.Saturday
            wt.WeeksInterval = 2
            wt.StartBoundary = Now
            wt.Repetition.Duration = TimeSpan.FromHours(11)
            wt.Repetition.Interval = TimeSpan.FromMinutes(10)
            td.Triggers.Add(wt)

            ' Add an action (shorthand) that runs Notepad
            td.Actions.Add(New ExecAction("notepad.exe", "C:\Test.log"))

            ' Register the task in the root folder
            ts.RootFolder.RegisterTaskDefinition(taskName, td)

            ' Remove the task we just created
            ts.RootFolder.DeleteTask(taskName)
        End Using
    End Sub

End Module
If you're really into shorthand code, here's almost the same functionality as the C# code above, but much shorter:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      new TaskService().AddTask("Test", new DailyTrigger { DaysInterval = 2 }, new ExecAction("notepad.exe", "c:\\test.log", null));
   }
}

New Post: Unable to create tasks from ASP.NET under W2008

0
0

Hello,

whenever I try to create tasks from an ASP.NET web app on a W2008 R2 server, I receive this exception:

 

System.Runtime.InteropServices.COMException: (39,8):Command:

 

The code I wrote resembles the samples I found here, and I already tried a lot of permutations of the RegisterTaskDefinition method, so I cannot understand what's the problem. Basically I call NewTask, add one action and one trigger, a start boundary and that's all, and finally I call RegisterTaskDefinition. I tried to call it without specifying credentials, or with my credentials, or with SYSTEM userId, with all the LogonTypes, I really tried a lot of things there, so I guess it must be something else.

If I create a task manually from the Task Scheduler UI I have no problems, and then if I try to modify the same task from the same ASP.NET web app I'm building everything works fine, the problem is only limited to the task creation phase. The ASP.NET app impersonates the same user account I use to create and edit the tasks manually from the Task Scheduler UI.

The very same code works fine when I use on my dev machine, which is an XP (hence using Task Scheduler 1.0).

Any thoughts?

Thanks

Wasp

New Post: Unable to create tasks from ASP.NET under W2008

0
0

Update: I was able to solve my problem moving from RegisterTaskDefinition to RegisterTask method (Xml definition). 

Source code checked in, #80839

0
0
* Added an event detail viewer to the TaskPropertiesControl mimicking the one from Windows

Source code checked in, #80875

0
0
* Added EventViewerDialog and continued work on History tab updates

New Comment on "Examples"

0
0
I have a question, how can I make this application grab scheduled tasks from another server on the network and allow people to run the tasks on demand?

New Comment on "Examples"

0
0
Also, is this library only for Desktop/Console apps? I'm trying to find one that works with asp.net.

New Comment on "Examples"

0
0
>>dbrewerton: The core library (not the UI library) can be used within ASP.NET but you'll need to be aware of execution permissions. Check the Discussions area for more information. To get and create tasks on a remote computer, specify that computer's name in the TaskService constructor. To execute tasks, retrieve an instance of the Task and use the Run method.

Updated Wiki: Examples

0
0
Below are some examples of how to use most of the functions of the library:

Connecting to a remote server
// Connect to the computer "REMOTE" using credentials
TaskService ts = new TaskService("\\REMOTE", "myusername", "MYDOMAIN", "mypassword");

Using the editor
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
   // Create a new task
   const string taskName = "Test";
   Task t = ts.AddTask(taskName, 
      new TimeTrigger() { StartBoundary = DateTime.Now + TimeSpan.FromHours(1), Enabled = false },
      new ExecAction("notepad.exe", "c:\\test.log", "C:\\"));

   // Edit task and re-register if user clicks Ok
   TaskEditDialog editorForm = new TaskEditDialog();
   editorForm.Editable = true;
   editorForm.RegisterTaskOnAccept = true;
   editorForm.Initialize(t);
   // ** The four lines above can be replaced by using the full constructor -- TaskEditDialog(t, true, true)
   editorForm.ShowDialog();

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Simple example
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
   // Create a new task definition and assign properties
   TaskDefinition td = ts.NewTask();
   td.RegistrationInfo.Description = "Does something";
   td.Principal.LogonType = TaskLogonType.InteractiveToken;

   // Add a trigger that will fire the task at this time every other day
   DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
   dt.Repetition.Duration = TimeSpan.FromHours(4);
   dt.Repetition.Interval = TimeSpan.FromHours(1);

   // Add a trigger that will fire every week on Friday
   td.Triggers.Add(new WeeklyTrigger { StartBoundary = DateTime.Today + TimeSpan.FromHours(2), DaysOfWeek = DaysOfTheWeek.Friday });

   // Add an action that will launch Notepad whenever the trigger fires
   td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

   // Register the task in the root folder
   const string taskName = "Test";
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Retrieve the task, change the trigger and re-register it
   Task t = ts.GetTask(taskName);
   td = t.Definition;
   td.Triggers[0].StartBoundary = DateTime.Today + TimeSpan.FromDays(7);
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Enumerate all tasks
void EnumAllTasks()
{
   using (TaskService ts = new TaskService())
      EnumFolderTasks(ts.RootFolder);
}

void EnumFolderTasks(TaskFolder fld)
{
   foreach (Task task in fld.Tasks)
      ActOnTask(task);
   foreach (TaskFolder sfld in fld.SubFolders)
      EnumFolderTasks(sfld);
}

void ActOnTask(Task t)
{
   // Do something interesting here
}

Complex example
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
bool preWin7 = true;

// Get the service on the local machine
using (TaskService ts = new TaskService())
{
   // Display version and server state
   Version ver = ts.HighestSupportedVersion;
   bool newVer = (ver >= new Version(1, 2));
   Console.WriteLine("Highest version: " + ver);
   Console.WriteLine("Server: {0} ({1})", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected");

   // Output all of the running tasks
   Console.WriteLine("Running tasks:");
   foreach (RunningTask rt in ts.GetRunningTasks(true))
   {
      if (rt != null)
      {
         Console.WriteLine("+ {0}, {1} ({2})", rt.Name, rt.Path, rt.State);
         if (ver.Minor > 0)
            Console.WriteLine("  Current Action: " + rt.CurrentAction);
      }
   }

   // Output all the tasks in the root folder with their triggers and actions
   TaskFolder tf = ts.RootFolder;
   Console.WriteLine("\nRoot folder tasks ({0}):", tf.Tasks.Count);
   foreach (Task t in tf.Tasks)
   {
      try
      {
         Console.WriteLine("+ {0}, {1} ({2})", t.Name, t.Definition.RegistrationInfo.Author, t.State);
         foreach (Trigger trg in t.Definition.Triggers)
            Console.WriteLine(" + {0}", trg);
         foreach (Action act in t.Definition.Actions)
            Console.WriteLine(" = {0}", act);
      }
      catch { }
   }

   // Output an enumeration of all folders under the root
   Console.WriteLine("\n***Checking folder enum***");
   TaskFolderCollection tfs = tf.SubFolders;
   if (tfs.Count > 0)
   {
      Console.WriteLine("\nSub folders:");
      try
      {
         foreach (TaskFolder sf in tfs)
            Console.WriteLine("+ {0}", sf.Path);
      }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   // Display information about the Microsoft folder
   if (newVer)
   {
      Console.WriteLine("\n***Checking folder retrieval***");
      try
      {
         TaskFolder sub = tf.SubFolders["Microsoft"];
         Console.WriteLine("\nSubfolder path: " + sub.Path);
      }
      catch (NotSupportedException) { }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   Console.WriteLine("\n***Checking task creation***");
   try
   {
      // Create a new task definition and assign properties
      TaskDefinition td = ts.NewTask();
      td.Data = "Your data";
      td.Principal.UserId = user;
      td.Principal.LogonType = TaskLogonType.InteractiveToken;
      td.RegistrationInfo.Author = "dahall";
      td.RegistrationInfo.Description = "Does something";
      td.RegistrationInfo.Documentation = "Don't pretend this is real.";
      td.Settings.DisallowStartIfOnBatteries = true;
      td.Settings.Enabled = false;
      td.Settings.ExecutionTimeLimit = TimeSpan.FromHours(2);
      td.Settings.Hidden = false;
      td.Settings.IdleSettings.IdleDuration = TimeSpan.FromMinutes(20);
      td.Settings.IdleSettings.RestartOnIdle = false;
      td.Settings.IdleSettings.StopOnIdleEnd = false;
      td.Settings.IdleSettings.WaitTimeout = TimeSpan.FromMinutes(10);
      td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal;
      td.Settings.RunOnlyIfIdle = false;
      td.Settings.RunOnlyIfNetworkAvailable = false;
      td.Settings.StopIfGoingOnBatteries = true;
      if (newVer)
      {
         td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA;
         //td.RegistrationInfo.SecurityDescriptorSddlForm = "O:COG:CGD::(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)";
         td.RegistrationInfo.Source = "Test App";
         td.RegistrationInfo.URI = new Uri("test://app");
         td.RegistrationInfo.Version = new Version(0, 9);
         td.Settings.AllowDemandStart = true;
         td.Settings.AllowHardTerminate = true;
         td.Settings.Compatibility = TaskCompatibility.V2;
         td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
         td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
         td.Settings.StartWhenAvailable = true;
         td.Settings.WakeToRun = false;
         td.Settings.RestartCount = 5;
         td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
      }

      if (preWin7)
      {
         // Create a trigger that fires 5 minutes after the system is booted
         BootTrigger bTrigger = (BootTrigger)td.Triggers.Add(new BootTrigger { Enabled = false });
         if (newVer) bTrigger.Delay = TimeSpan.FromMinutes(5);
      }

      // Create a trigger that fires every other day randomly between 6:00 a.m. and 8:00 a.m.
      DailyTrigger dTrigger = (DailyTrigger)td.Triggers.Add(new DailyTrigger());
      dTrigger.StartBoundary = DateTime.Today + TimeSpan.FromHours(6);
      dTrigger.DaysInterval = 2;
      if (newVer) dTrigger.RandomDelay = TimeSpan.FromHours(2);

      if (newVer)
      {
         if (preWin7)
         {
            // Create a trigger that will fire on a system security event
            EventTrigger eTrigger = (EventTrigger)td.Triggers.Add(new EventTrigger());
            eTrigger.SetBasic("Security", "VSSAudit", 25);
            eTrigger.ValueQueries.Add("Name", "Value");
         }

         // Create a trigger that fires 5 minutes after this task is registered
         td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromMinutes(5) });

         if (preWin7)
         {
            // Create triggers that fire after various system states are changed
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleConnect, UserId = user });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleDisconnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteConnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteDisconnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionLock, UserId = user });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionUnlock });
         }
      }

      // Create a trigger that fires when the system is idle
      td.Triggers.Add(new IdleTrigger());

      // Create a trigger that fires 15 minutes after the current user logs on and then every 1000 seconds after that
      LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
      if (newVer)
      {
         lTrigger.Delay = TimeSpan.FromMinutes(15);
         lTrigger.UserId = user;
         lTrigger.Repetition.Interval = TimeSpan.FromSeconds(1000);
      }

      // Create a trigger that fires on the 3rd, 6th, 10th, 18th, and last days of July and November and stops triggering 90 days from now
      MonthlyTrigger mTrigger = (MonthlyTrigger)td.Triggers.Add(new MonthlyTrigger());
      mTrigger.DaysOfMonth = new int[] { 3, 6, 10, 18 };
      mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November;
      if (newVer) mTrigger.RunOnLastDayOfMonth = true;
      mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90);

      // Create a trigger that fires every day of the first and last week of December and January
      MonthlyDOWTrigger mdTrigger = (MonthlyDOWTrigger)td.Triggers.Add(new MonthlyDOWTrigger());
      mdTrigger.DaysOfWeek = DaysOfTheWeek.AllDays;
      mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December;
      if (newVer) mdTrigger.RunOnLastWeekOfMonth = true;
      mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;

      // Create a trigger that fires 1 minute from now and then every 15 minutes for the next 7 days.
      TimeTrigger tTrigger = (TimeTrigger)td.Triggers.Add(new TimeTrigger());
      tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1);
      tTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(7);
      if (newVer) tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(15);
      if (newVer) tTrigger.Id = "Time test";
      tTrigger.Repetition.Duration = TimeSpan.FromMinutes(20);
      tTrigger.Repetition.Interval = TimeSpan.FromMinutes(15);
      tTrigger.Repetition.StopAtDurationEnd = true;

      // Create a trigger that fires every third week on Monday
      WeeklyTrigger wTrigger = (WeeklyTrigger)td.Triggers.Add(new WeeklyTrigger());
      wTrigger.DaysOfWeek = DaysOfTheWeek.Monday;
      wTrigger.WeeksInterval = 3;

      // Create an action which opens a log file in notepad
      td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
      if (newVer)
      {
         // Create an action which shows a message to the interactive user
         td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
         // Create an action which sends an email
         td.Actions.Add(new EmailAction("Testing", "dahall@codeplex.com", "user@test.com", "You've got mail.", "mail.myisp.com"));
         // Create an action which loads a COM object and calls the ITaskHandler interface
         td.Actions.Add(new ComHandlerAction(new Guid("CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734"), string.Empty));
      }

      // Register the task definition (saves it) in the security context of the interactive user
      tf.RegisterTaskDefinition("Test", td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null);
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.ToString());
   }

   // Display information about the newly created task
   Task runningTask = tf.Tasks["Test"];
   Console.WriteLine("\nNew task will run at " + runningTask.NextRunTime);
   Console.WriteLine("\nNew task triggers:");
   for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Triggers[i]);
   Console.WriteLine("\nNew task actions:");
   for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Actions[i]);

   // Remove the task we just created since this was just a test
   tf.DeleteTask("Test");
}

Task history example
Only works with release 1.6.2 or source code drop 66948 and later and requires the inclusion of the TaskSchedulerEditor assembly.
TaskEventLog log = new TaskEventLog(task.Path);
List<ListViewItem> c = new List<ListViewItem>(100);
foreach (TaskEvent item in log)
   c.Add(new ListViewItem(new string[] { item.Level, item.TimeCreated.ToString(), item.EventId.ToString(),
      item.TaskCategory, item.OpCode, item.ActivityId.ToString() }));

Released: Release 1.9 (Oct 29, 2012)

0
0
Many bug fixes, full support for Windows 7 and Windows 8 additions to core library, and an enhanced editor to allow editing of all properties, since the 1.8.3 release. SeeSource Code for full details of changes.

Download Descriptions
  • TaskScheduler.zip - Includes the base library (Microsoft.Win32.TaskScheduler.dll) with no UI code. Works with .NET 2.0 and higher. Add this assembly as a reference to interact with Task Scheduler on all systems with IE4 and later. This package is also available via NuGet with package nameTaskScheduler.
  • TaskSchedulerEditor.zip - Includes the UI library (Microsoft.Win32.TaskSchedulerEditor.dll) with all supporting assemblies. Works with .NET 3.5 and higher. Add this assembly as a reference along with Microsoft.Win32.TaskScheduler.dll to get editor controls and dialogs that allow for viewing and editing tasks, triggers, actions, lists, etc. This package is also available viaNuGet with package nameTaskSchedulerEditor.
  • TaskSchedulerHelp.zip - Includes the Microsoft Help (VS2010) compatible help files for both the base and editor libraries. Extract all files and then run Install_TaskScheduler.bat to integrate the help.

Updated Release: Release 1.9 (Oct 29, 2012)

0
0
Many bug fixes, full support for Windows 7 and Windows 8 additions to core library, and an enhanced editor to allow editing of all properties, since the 1.8.3 release. See Source Code for full details of changes.

Download Descriptions
  • TaskScheduler.zip - Includes the base library (Microsoft.Win32.TaskScheduler.dll) with no UI code. Works with .NET 2.0 and higher. Add this assembly as a reference to interact with Task Scheduler on all systems with IE4 and later. This package is also available via NuGet with package name TaskScheduler.
  • TaskSchedulerEditor.zip - Includes the UI library (Microsoft.Win32.TaskSchedulerEditor.dll) with all supporting assemblies. Works with .NET 3.5 and higher. Add this assembly as a reference along with Microsoft.Win32.TaskScheduler.dll to get editor controls and dialogs that allow for viewing and editing tasks, triggers, actions, lists, etc. This package is also available via NuGet with package name TaskSchedulerEditor.
  • TaskSchedulerHelp.zip - Includes the Microsoft Help (VS2010) compatible help files for both the base and editor libraries. Extract all files and then run Install_TaskScheduler.bat to integrate the help.

New Post: How to auto-delete a task after running once?

0
0

I want to create a task that does the following:

- Run once immediately

- Self-delete task after running

How to implement this? I looked around the documentation, but couldn't find one. Appreciate any pointers.

Viewing all 2206 articles
Browse latest View live




Latest Images