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

Commented Issue: Use a Group Managed service account to run a schedule task and make it "Run whether user is logged on or not"? [12362]

0
0
These two ways are not working, here is my test code, I test it on windows server 2012R2:
```
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.TaskScheduler;

namespace WrapperDemo
{
internal static class Program
{
public static void Main(string[] args)
{
try
{
var action = new ExecAction(@"C:\PowerSlim\test.cmd");
var trigger = new DailyTrigger(1);
trigger.StartBoundary = DateTime.Today.AddHours(20);
TaskService.Instance.AddTask("msaTask", trigger, action, @"er\zz$", "", TaskLogonType.Password);
}
catch (COMException exception)
{
Console.WriteLine(exception.ToString());
}

}
}
}

```
I got exception like following on the console output:

System.Runtime.InteropServices.COMException (0x8007052E): The username or password is incorrect. (Exception from HRESULT: 0x8007052E)
at Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)
at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String Path, TaskDefinition definition, TaskCreation createType, String UserId, String password, TaskLogonType LogonType, String sddl)
at Microsoft.Win32.TaskScheduler.TaskService.AddTask(String path, Trigger trigger, Action action, String UserId, String Password, TaskLogonType LogonType)
at WrapperDemo.Program.Main(String[] args) in C:\Users\lhuang2\Documents\Visual Studio 2015\Projects\WrapperDemo\WrapperDemo\Program.cs:line 20
Comments: ** Comment from web user: alvin_chen **

@dahall, I tried v4.5.2 in the attachment, it works.
But we need to work in .net framework 4.0, and we use NuGet to manage this library, so hope this fixing could be available soon. Thanks!


New Post: Do I need to dispose all the instances (Task, Trigger, Action, etc) which implemented interface “IDisposable”?

New Post: Tick "Run whether user is logged in or not" Programmatically

0
0
Would this work in Task Scheduler version 1.0 as well ?

New Post: how to use a Group Managed service account to run a schedule task and make it "Run whether user is logged on or not"?

0
0
Hi dahall, I tried, your assemblies work well.

New Post: Do I need to dispose all the instances (Task, Trigger, Action, etc) which implemented interface “IDisposable”?

0
0
No. Those are created and disposed internally. Technically, due to the beauty of garbage disposal in C#, you don't need to manually dispose of anything. However, if you are worried about memory consumption while running your app, disposing the TaskService instance should clean up all memory previously used by the library.

Closed Unassigned: The system cannot find the path specified. [12350]

0
0
Hi,

After some changes library cannot get data from remote server.
Details: I use win7 and try to get state of task on win2003. TaskService is used with forceV1=true.
Code to reproduce:
```
using (TaskService ts = new TaskService(targetServer2003, user, domain, pwd, true ))
{
List<TaskState> taskList = new List<TaskState>();
foreach (Task task in ts.RootFolder.Tasks)
taskList.Add(task.State);// error occurs here
}
```
Error:
```
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)

at Microsoft.Win32.TaskScheduler.V1Interop.ITaskScheduler.Activate(String Name, Guid& riid)
at Microsoft.Win32.TaskScheduler.TaskService.GetTask(ITaskScheduler iSvc, String name)
at Microsoft.Win32.TaskScheduler.Task.V1Reactivate()
at Microsoft.Win32.TaskScheduler.Task.get_State()
at TestRemoteConnectionTo2003.Program.Main(String[] args) in c:\users\akolpako\documents\visual studio 2015\Projects\TestRemoteConnectionTo2003\TestRemoteConnectionTo2003\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
```
The bug had appeared after changes in TaskService.cs. After adding the next line:
name = name.TrimStart('\\');
```
internal static V1Interop.ITask GetTask(V1Interop.ITaskScheduler iSvc, string name)
{
name = name.TrimStart('\\');
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
try
{
return iSvc.Activate(name, ref ITaskGuid);
}
catch (System.UnauthorizedAccessException)
{
// TODO: Take ownership of the file and try again
throw;
}
catch (System.ArgumentException)
{
return iSvc.Activate(name + ".job", ref ITaskGuid);
}
catch { throw; }
}
```
Some time method is called with path argument instead of name. (For example when you are reading a status). It can lead to an error.
Path that leads to the error:
![Image](http://i68.tinypic.com/15i50mx.png)

New Post: "StartWhenAvailable" not checked in Scheduler

0
0
Hey there,

First of all, thanks for making this Wrapper. It's amazing.

I need to change desktop background every day based on time user picks. If machine is not working I need this task to start after user logs on at some point.

This is the code that I have at the moment :
using (TaskService taskSer = new TaskService())
            {
                TaskDefinition td = taskSer.NewTask();
                DailyTrigger dt = new DailyTrigger();
                dt.StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, startHour.Hours, startHour.Minutes, startHour.Seconds);

                taskSer.AddTask("Task", dt, new ExecAction(execPath));

                td.Settings.StartWhenAvailable = true;
                td.Settings.Compatibility = TaskCompatibility.V2_3;
                td.Settings.RestartInterval = TimeSpan.Zero;
            }
However, when I go to Task Scheduler, Settings tab, checkbox for starting the task after missing it, is not checked.

How can I set "StartWhenAvailable" checkbox marked through the code ?

I did check Discussions and only found one topic which covered this question, but it doesn't apply to me as I tried already to set RestartInterval to TimeInterval.Zero. I need this task to be infinite, so I'm not sure how would I set EndBoundry in that case ?

Thanks,
S. M.

Source code checked in, #98063

0
0
* Fixed problems with Task.Run and RunEx methods * Removed check for password != null when registering a task to allow for cases where password is valid as empty * Version 2.5.17 * Added .NET 4 assemblies back into NuGet

Source code checked in, #98064

Source code checked in, #98065

Released: Release 2.5.17 (Apr 07, 2016)

0
0
Update history
Version 2.5.17
  • Added back in .NET 4 builds
  • Fixed RegisterTaskDefinition for tasks setting password to null
  • Fixed Task.Run and RunEx methods
Version 2.5.16
  • Event and Security UI bug fixes
  • Changed package to .NET 4.5.2 from 4.0
Version 2.5.15
  • Editor fixes
Version 2.5.14
  • Fixes to TaskEventWatcher, Trigger.StartDate and assoc UI
Version 2.5.13
  • More bug fixes (see History)
  • Completed first revision of a diagnostic tool
Version 2.5.12
  • A few bug fixes (see History)
Version 2.5.8
  • A few bug fixes (see History)
  • Updated NuGet to include symbols
Version 2.5.7
  • Fixed V1 error with ActionCollection.Clear
  • Added TaskSchedulerConfig project (incomplete) to help identify connection problems on V1 and V2 systems
Version 2.5.6
  • Bug fixes (V1 actions count and retention)
Version 2.5.5
  • Bug fixes (V1 registration validation & Task.IsActive)
Version 2.5.4
  • Added TaskEventWatcher component that enables watching task folders or tasks for changes and updated TaskListView and TaskHistoryControl with that feature (seesample code)
  • Fixed bug with context menu for lists that would display it in wrong position
Version 2.5.3
  • Fixed major bug when registering tasks with well known groups and built-in accounts ("Everyone", "SYSTEM", etc.) -- Sorry everyone.
  • Removed data contract attributes
Version 2.5.0
  • Bug fixes
  • Added ability for V1 tasks to support almost all V2 properties including the support of multiple action types of all action variants.
  • Bi-directional support for XML across V1 and V2
Version 2.4
  • A number of bug fixes for Windows 10.
  • Added support for .NET 2.0, 3.5 and 4.0
  • Added security handling and version compatibility handling (for connecting to up or down-stream versions)
  • Bug fixes
  • Enhancements to history control and event trigger editor
  • Compensation for deprecated email and message actions on Win8
  • Improved performance and marshalling.
Version 2.3
  • A more modern editor has been added as TaskOptionsEditor.
Version 2.0
  • Some bug fixes
  • Better support for Windows 8 additions to core library
  • Addition of Fluent syntax and crontab syntax
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. Separate assemblies for .NET 2.0, 3.5 and 4.0. 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 2.0 and higher. Separate assemblies for .NET 2.0, 3.5 and 4.0. 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 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 2.5.17 (Apr 07, 2016)

0
0
Update history
Version 2.5.17
  • Added back in .NET 4 builds
  • Fixed RegisterTaskDefinition for tasks setting password to null
  • Fixed Task.Run and RunEx methods
Version 2.5.16
  • Event and Security UI bug fixes
  • Changed package to .NET 4.5.2 from 4.0
Version 2.5.15
  • Editor fixes
Version 2.5.14
  • Fixes to TaskEventWatcher, Trigger.StartDate and assoc UI
Version 2.5.13
  • More bug fixes (see History)
  • Completed first revision of a diagnostic tool
Version 2.5.12
  • A few bug fixes (see History)
Version 2.5.8
  • A few bug fixes (see History)
  • Updated NuGet to include symbols
Version 2.5.7
  • Fixed V1 error with ActionCollection.Clear
  • Added TaskSchedulerConfig project (incomplete) to help identify connection problems on V1 and V2 systems
Version 2.5.6
  • Bug fixes (V1 actions count and retention)
Version 2.5.5
  • Bug fixes (V1 registration validation & Task.IsActive)
Version 2.5.4
  • Added TaskEventWatcher component that enables watching task folders or tasks for changes and updated TaskListView and TaskHistoryControl with that feature (see sample code)
  • Fixed bug with context menu for lists that would display it in wrong position
Version 2.5.3
  • Fixed major bug when registering tasks with well known groups and built-in accounts ("Everyone", "SYSTEM", etc.) -- Sorry everyone.
  • Removed data contract attributes
Version 2.5.0
  • Bug fixes
  • Added ability for V1 tasks to support almost all V2 properties including the support of multiple action types of all action variants.
  • Bi-directional support for XML across V1 and V2
Version 2.4
  • A number of bug fixes for Windows 10.
  • Added support for .NET 2.0, 3.5 and 4.0
  • Added security handling and version compatibility handling (for connecting to up or down-stream versions)
  • Bug fixes
  • Enhancements to history control and event trigger editor
  • Compensation for deprecated email and message actions on Win8
  • Improved performance and marshalling.
Version 2.3
  • A more modern editor has been added as TaskOptionsEditor.
Version 2.0
  • Some bug fixes
  • Better support for Windows 8 additions to core library
  • Addition of Fluent syntax and crontab syntax
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. Separate assemblies for .NET 2.0, 3.5 and 4.0. 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 2.0 and higher. Separate assemblies for .NET 2.0, 3.5 and 4.0. 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 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: "StartWhenAvailable" not checked in Scheduler

0
0
Close, but you mixed the quick model (using AddTask) with the full control model (which uses TaskDefinition and RegisterTaskDefinition). Your corrected code would be:
TaskDefinition td = TaskService.Instance.NewTask();
// Setup and add trigger
DailyTrigger dt = new DailyTrigger();
dt.StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, startHour.Hours,
    startHour.Minutes, startHour.Seconds);
td.Triggers.Add(dt);
// Setup and add action
td.Actions.Add(execPath);
// Add settings
td.Settings.StartWhenAvailable = true;
td.Settings.Compatibility = TaskCompatibility.V2_3;
td.Settings.RestartInterval = TimeSpan.Zero;
// Register definition
TaskService.Instance.RootFolder.RegisterTaskDefinition("Task", td);

Updated Wiki: Examples

0
0

Examples Home Page

You can go to these pages for more sample code:
Below are some examples of how to use most of the functions of the library:
On all these examples, if you get an error on ambiguous references for 'Action', please preface it with 'Microsoft.Win32.TaskScheduler.Action'.

Using the editor
// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Create a new taskconststring 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 editorForm = new TaskEditDialog(t, true, true);
   editorForm.ShowDialog();

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

Simple task creation
// Get the service on the local machineusing (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(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 folderconststring taskName = "Test";
   ts.RootFolder.RegisterTaskDefinition(taskName, td);
}

Get and delete a task
void GetAndDeleteTask(taskName)
{
   // Retrieve the task, change the trigger and re-register it.// A taskName by itself assumes the root folder (e.g. "MyTask")// A taskName can include folders (e.g. "MyFolder\MySubFolder\MyTask")
   Task t = ts.GetTask(taskName);
   if (t == null) return;
   t.Definition.Triggers[0].StartBoundary = DateTime.Today + TimeSpan.FromDays(7);
   t.RegisterChanges();

   // 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 machineusing (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 folderif (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.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 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 = newint[] { 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");
}

XML example
Tasks can be saved or created from scratch in XML and then registered directly as an alternative to setting individual properties.
// Save a Task's XML to a filestring xml = TaskService.Instance.GetTask("\\Temp").Xml;
System.IO.File.WriteAllText("localfile.xml", td.XmlText, System.Text.Encoding.Unicode);
// Create a Task using XML with user information
TaskService.Instance.RootFolder.RegisterTask("NewTask1", xml, TaskCreation.Create,
   "SYSTEM", null, TaskLogonType.SystemAccount);
// Create a Task directly from a file
TaskService.Instance.RootFolder.ImportTask("NewTask2", "localfile.xml");
// Load an XML file for editing, change a property, and register
TaskDefintion td  = TaskService.Instance.NewTask();
td.XmlText = System.IO.File.ReadAllText("localfile.xml");
td.Settings.AllowDemandStart = true;
TaskService.Instance.RootFolder.RegisterTaskDefinition("NewTask3", td);

Fluent example
The library also exposes a Fluent syntax for accomplishing most functions. Below are a number of examples.
using (TaskService ts = new TaskService())
{
   ts.Execute("notepad.exe").WithArguments(@"c:\temp\music.txt").Once().Starting(2013, 11, 11, 11, 0, 0).RepeatingEvery(TimeSpan.FromMinutes(5)).AsTask("Test");

   ts.Execute("notepad.exe").Every(2).Days().Starting("12/25/2013 7:00pm").AsTask("Test");

   ts.Execute("notepad.exe").Every(3).Weeks().AsTask("Test");

   ts.Execute("notepad.exe").OnAll(DaysOfTheWeek.Monday).In(WhichWeek.FirstWeek).Of(MonthsOfTheYear.January).AsTask("Test");

   ts.Execute("notepad.exe").InTheMonthOf(MonthsOfTheYear.January).OnTheDays(1, 3, 5).AsTask("Test");

   ts.Execute("notepad.exe").OnBoot().AsTask("Test");

   ts.Execute("notepad.exe").OnIdle().AsTask("Test");

   ts.Execute("notepad.exe").OnStateChange(TaskSessionStateChangeType.ConsoleConnect).AsTask("Test");

   ts.Execute("notepad.exe").AtLogonOf("AMERICAS\\dahall").AsTask("Test");

   ts.Execute("notepad.exe").AtTaskRegistration().AsTask("Test");
}

Task history example
If you use the TaskEventLog constructor which specifies a remote machine, you will need to use impersonation to logon to an account with privileges to the remote machine before instantiating the TaskEventLog.
TaskEventLog log = new TaskEventLog(task.Path);
List<ListViewItem> c = new List<ListViewItem>(100);
foreach (TaskEvent item in log)
   c.Add(new ListViewItem(newstring[] { item.Level, item.TimeCreated.ToString(),
      item.EventId.ToString(), item.TaskCategory, item.OpCode,
      item.ActivityId.ToString() }));

New Post: "StartWhenAvailable" not checked in Scheduler

0
0
Thank you so much dahall !

I realized my mistake as well now :)

I'm sure this topic will be of use to someone else too.

Marked as answer.

Closed Issue: Use a Group Managed service account to run a schedule task and make it "Run whether user is logged on or not"? [12362]

0
0
These two ways are not working, here is my test code, I test it on windows server 2012R2:
```
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.TaskScheduler;

namespace WrapperDemo
{
internal static class Program
{
public static void Main(string[] args)
{
try
{
var action = new ExecAction(@"C:\PowerSlim\test.cmd");
var trigger = new DailyTrigger(1);
trigger.StartBoundary = DateTime.Today.AddHours(20);
TaskService.Instance.AddTask("msaTask", trigger, action, @"er\zz$", "", TaskLogonType.Password);
}
catch (COMException exception)
{
Console.WriteLine(exception.ToString());
}

}
}
}

```
I got exception like following on the console output:

System.Runtime.InteropServices.COMException (0x8007052E): The username or password is incorrect. (Exception from HRESULT: 0x8007052E)
at Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)
at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String Path, TaskDefinition definition, TaskCreation createType, String UserId, String password, TaskLogonType LogonType, String sddl)
at Microsoft.Win32.TaskScheduler.TaskService.AddTask(String path, Trigger trigger, Action action, String UserId, String Password, TaskLogonType LogonType)
at WrapperDemo.Program.Main(String[] args) in C:\Users\lhuang2\Documents\Visual Studio 2015\Projects\WrapperDemo\WrapperDemo\Program.cs:line 20
Comments: Fixed in 2.5.17 released 4/7/16

Closed Issue: Error using RegisterTaskDefinition on Window10 Professional When calling "RegisterTaskDefinition", [12261]

0
0
Error using RegisterTaskDefinition on Window10 Professional When calling "RegisterTaskDefinition", the error I am getting is:

"Die angegebene Domäne ist nicht vorhanden, oder es konnte keine Verbindung hergestellt werden"
The specified domain does not exist, or no connection could be made

```
Using ts As New TaskService()
' Create a new task definition and assign properties
Dim td As TaskDefinition = ts.NewTask
td.RegistrationInfo.Description = "Does something"

' Add a trigger that will, starting tomorrow, fire every other week on Monday
' and Saturday and repeat every 10 minutes for the following 11 hours
Dim wt As New WeeklyTrigger()
wt.StartBoundary = DateTime.Today.AddDays(1)
wt.DaysOfWeek = DaysOfTheWeek.Monday Or DaysOfTheWeek.Saturday
wt.WeeksInterval = 2
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("Test", td, TaskCreation.Create, "SYSTEM",, TaskLogonType.ServiceAccount)
End Using
```

Closed Issue: System.IO.FileNotFoundException when registering task under 64 bit Windows 10 Pro Insider Preview Build 10158 [12142]

0
0
At the moment I'm running into this problem on 64 bit Windows 10 Pro Insider Preview Build 10158. Same call works on 64 bit Windows 8.1 Pro.

System.IO.FileNotFoundException, The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
at Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)
at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String Path, TaskDefinition definition, TaskCreation createType, String UserId, String password, TaskLogonType LogonType, String sddl)

Used .NET-Framework 2.0 - Version 2.3.4.0

In fact I'm using the TaskCreation.CreateOrUpdate enum value and the process is elevated. Let me give you some more information:

I'm using a RegistrationTrigger, with a delay of 8 seconds and a EndBoundary of 20 seconds.
* RunLevel is TaskRunLevel.LUA
* DeleteExpiredTaskAfter is 40 seconds
* Principal.UserId is the UserName of the Win32_ComputerSystem ManagementObject (Example: WIN-GVLEGB4ESV6\Test )

```
using System;
using Microsoft.Win32.TaskScheduler;
using System.Management;

namespace TestTaskScheduler
{
class Program
{
static void Main(string[] args)
{

var ts = new TaskService();

TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "some description";
td.Principal.LogonType = TaskLogonType.InteractiveToken;

var computerSystemClass = new ManagementClass("Win32_ComputerSystem");
var computerSystems = computerSystemClass.GetInstances();
var enumerator = computerSystems.GetEnumerator();
while (enumerator.MoveNext())
{
var computerSystem = enumerator.Current;
td.Principal.UserId = (string)computerSystem["UserName"];
}

td.Actions.Add(new ExecAction("cmd.exe", "-someparameter"));

// Create Trigger
var trigger = new RegistrationTrigger { Enabled = true };
trigger.Delay = TimeSpan.FromSeconds(8);
trigger.EndBoundary = DateTime.Now + TimeSpan.FromSeconds(20);
td.Triggers.Add(trigger);

TaskFolder tf = ts.RootFolder;

td.Principal.RunLevel = TaskRunLevel.LUA;

td.Settings.StartWhenAvailable = true;
td.Settings.Hidden = false;
td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.StopIfGoingOnBatteries = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromSeconds(40);

TaskFolder testFolder = null;

foreach (TaskFolder taskFolder in tf.SubFolders)
{
if (taskFolder.Name.Equals("TEST", StringComparison.OrdinalIgnoreCase))
{
testFolder = taskFolder;
}
}

if (testFolder == null)
testFolder = tf.CreateFolder("TEST");

testFolder.RegisterTaskDefinition("Start", td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken);
Console.ReadKey();
}
}
}
```

Closed Unassigned: Error using RegisterTaskDefinition on Window10 Professional [12169]

0
0
______Error using RegisterTaskDefinition on Window10 Proffessional______

When calling "RegisterTaskDefinition", the error I am getting is:

the task xml contains a value which is incorrectly formatted or out of range
Exception from HResult:0x80041318

Any help is appreciated.

Updated Wiki: Home

0
0
This project provides a wrapper for the Windows Task Scheduler. It aggregates the multiple versions, provides an editor and allows for localization.

NuGet
This project's assemblies are available via NuGet. Main Library
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). Core features include:
  • Separate, functionally identical, libraries for .NET 2.0 and 4.0.
  • Unlike the base library, this wrapper helps to create and view tasks up and down stream.
  • Written in C#, but works with any .NET language including scripting languages (e.g. PowerShell).
  • Supports almost all V2 native properties, even under V1 systems.
  • Maintain EmailAction and ShowMessageAction using PowerShell scripts for systems after Win8 where these actions have been deprecated
  • Supports all action types (not just ExecAction) on V1 systems (XP/WS2003) and earlier (if PowerShell is installed).
  • Supports multiple actions on V1 systems (XP/WS2003). Native library only supports a single action.
  • Supports serialization to XML for both 1.0 and 2.0 tasks (base library only supports 2.0)
  • Supports task validation for targeted version.
  • Supports secure task reading and maintenance.
  • Fluent methods for task creation.
  • Cron syntax for trigger creation.
  • Supports reading "custom" triggers under Win8 and later.
  • Numerous work-arounds and checks to compensate for base library shortcomings.
The project supports a number of languages and, upon request, is ready to support others. The currently supported languages include: English, Spanish, Italian, French, Chinese (Simplified), German.

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

UI Library
There is a second library that includes localized and localizable GUI editors and a wizard for tasks which mimic the ones in Vista and later and adds optional pages for new properties. Following is the list of available UI controls:
  • A DropDownCheckList control that is very useful for selecting flag type enumerations.
  • A FullDateTimePicker control which allows both date and time selection in a single control.
  • A CredentialsDialog class for prompting for a password which wraps the Windows API.
  • Simplified classes for pulling events from the system event log.
  • Action editor dialog
  • Trigger editor dialog
  • Task editor dialog and tabbed control
  • Event viewer dialog
  • Task / task folder selection dialog
  • Task history viewer
  • Task run-times viewer
  • Task creation wizard
  • Task service connection dialog
COM Handler Project Template
If you are writing your own custom Task Scheduler COM Handler based on the ITaskHandler interface, there is a project template available that will stub out the majority of the work to create it in C# and a sample to show a complete one. If running your own code, this model provides much better interaction, control and memory management than running an executable.

Sample Code
There is a help file included with the download that provides an overview of the various classes. There are numerous examples under the "Documentation" tab.

You can perform a number of actions in a single line of code:

// Run a program every day on the local machine
TaskService.Instance.AddTask("Test", QuickTriggerType.Daily, "myprogram.exe", "-a arg");

// Run a custom COM handler on the last day of every month
TaskService.Instance.AddTask("Test", new MonthlyTrigger { RunOnLastDayOfMonth = true }, 
    new ComHandlerAction(new Guid("{CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734}")));

For many more options, use the library classes to build a complex task. Below is a brief example of how to use the library from C#.

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   staticvoid Main(string[] args)
   {
      // Get the service on the local machineusing (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);
      }
   }
}

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.
Viewing all 2206 articles
Browse latest View live




Latest Images