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

New Post: How to enable a task in task scheduler using C#?

$
0
0
You can set alreadyPresentTask.Definition.Settings.Enabled = true before calling RegisterChanges. This will ensure the task is enabled and you do not have to set the alreadyPresentTask.Enabled property.

Also, FindTask is a bit of a risky method in that it is non-deterministic. It will return the first task in any folder it finds whose name matches the one provided to the method. You are much safer to use the GetTask method and provide the full path to the task as it is deterministic. Also, either your if (action is ExecAction) or your if (null == execAction) statement is unnecessary as they both check the same condition.

I believe the problem is related to how C# handles references and potentially the wrapper not accommodating that well. To resolve, I would try something like:
// 1. If using the local instance of the Task Scheduler, you can use the static Instance property.
// 2. Prepend the exact folder name in GetTask.
var alreadyPresentTask = TaskService.Instance.GetTask("\\" + settings.TaskSchedulerTaskName);
if (alreadyPresentTask != null)
{
  // 3. Avoid re-registering the task if not needed.
  bool changed = false;
  for (int i = 0; i < alreadyPresentTask.Definition.Actions.Count; i++)
  {
    ExecAction execAction = alreadyPresentTask.Definition.Actions[i] as ExecAction;
    if (execAction != null)
    {
      var root = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
      var newPath = System.IO.Path.Combine(root, Path.GetFileName(execAction.Path));

      // 4. I believe that by creating a new action and replacing the old you
      //    will avoid the reference problem.
      alreadyPresentTask.Definition.Actions[i] = new ExecAction(newPath, execAction.Arguments, root);

      changed = true;
    }
  }
  if (changed)
  {
    // 5. Using this setting will ensure the task stays enabled
    alreadyPresentTask.Definition.Settings.Enabled = true;
    alreadyPresentTask.RegisterChanges();
  }
}

Viewing all articles
Browse latest Browse all 2206

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>