Ephedra
Ephedra

Reputation: 881

How to set "Do not stored password.The task will only have access to local computer resources programmatically in TaskScheduler

I programmatically create a task of TaskScheduler and run it. I am using the following code:

var taskDefinition = taskService.NewTask();
taskDefinition.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;
taskDefinition.RegistrationInfo.Description = "Runs Programm";

// TaskLogonType.S4U = run wether user is logged on or not 
taskDefinition.Principal.LogonType = TaskLogonType.S4U;

var action = new ExecAction(path, arguments);
taskDefinition.Actions.Add(action);
taskService.RootFolder.RegisterTaskDefinition("TaskName", taskDefinition);

//get task:
var task = taskService.RootFolder.GetTasks().Where(a => a.Name == "TaskName").FirstOrDefault();

try
{
    task.Run();
}
catch (Exception ex)
{
    log.Error("Error starting task in TaskSheduler with message: " + ex.Message);
}

The task is created and I can see it in the TaskScheduler Window, but there is one checkbox I want to be unchecked. It is called "Do not store password. The task will only have access to local resources"

I found out how to check the radiobutton above it that says "Run whether user is logged on or not" This is set via:

taskDefinition.Principal.LogonType = TaskLogonType.S4U;

But how do I also set the Checkbox beneath to false?

Upvotes: 1

Views: 4588

Answers (2)

Ephedra
Ephedra

Reputation: 881

I finally solved this by:

taskService.RootFolder.DeleteTask("TaskName", false);

var taskDefinition = taskService.NewTask();                        
taskDefinition.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;

taskDefinition.RegistrationInfo.Description = "Runs Task with arguments: " + arguments;
taskDefinition.Principal.LogonType = TaskLogonType.InteractiveTokenOrPassword;

var action = new ExecAction(path, arguments);
taskDefinition.Actions.Add(action);
taskService.RootFolder.RegisterTaskDefinition("TaskName", taskDefinition, TaskCreation.Create, "domain\\user", password, TaskLogonType.InteractiveTokenOrPassword);

//get task:
var task = taskService.RootFolder.GetTasks().Where(a => a.Name == ("TaskName").FirstOrDefault();
log.Info("Start task " + task.Name + " with arguemtns " + arguments);

try
{
    task.Run();
}
catch (Exception ex)
{
    log.Error("Error starting task in TaskSheduler with message: " + ex.Message);
}

Upvotes: 4

Tom Söhne
Tom Söhne

Reputation: 522

Docs say

Use an existing interactive token to run a task. The user must log on using a service for user (S4U) logon. When an S4U logon is used, no password is stored by the system and there is no access to either the network or encrypted files

so i guess it does not matter if you set the checkbox for storing password or not.

that should apply for TASK_LOGON_S4U and TASK_LOGON_SERVICE_ACCOUNT

Upvotes: 0

Related Questions