This project has moved. For the latest updates, please go here.

How do I create a task that only run with a particular user account?

Mar 15, 2012 at 8:58 AM
Edited Mar 15, 2012 at 8:59 AM

Hi,

Anybody can show me the sample code of the below:

1. How do I create a task that only run with a particular user account?

2. How do I delete a task that was created with a particular user account?

3. How do I update a task that was created with a particular user account?

Thanks.

Coordinator
Mar 15, 2012 at 5:24 PM

You must connect to the server using the TaskService constructor specifying either the account or an account with Administrator privileges. This will let you create, delete or update a task using that account. To create or update a task that will run as a specific user, you must provide that user’s information in the RegisterTaskDefinition method.

// Get the service on the local machine using a domain account
using (TaskService ts = new TaskService(null, userName, userDomain, userPassword))
{
  // Create a new task definition and assign properties
  TaskDefinition td = ts.NewTask();
  td.RegistrationInfo.Description = "Does something";
  td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
  td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
  ts.RootFolder.RegisterTaskDefinition("Test", td, TaskCreation.CreateOrUpdate, userDomain + "\\" + userName, userPassword, TaskLogonType.Password);
  
  // Retrieve the task and modify it
  Task t = ts.GetTask("Test");
  t.TaskDefinition.Triggers[0].StartBoundary = DateTime.Today.AddDays(4);
  ts.RootFolder.RegisterTaskDefinition("Test", t.TaskDefinition, TaskCreation.CreateOrUpdate, userDomain + "\\" + userName, userPassword, TaskLogonType.Password);

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

Mar 19, 2012 at 7:06 AM

Hi,

Thanks.