How to set "run only at login" and "run as" using TaskScheduler in C #?

I am trying to use the C # Task Scheduler Manager to programmatically create scheduled tasks on a Windows system. I can create tasks, but I can not get them to start only when registering an account:

enter image description here

I look around and I found another question that was asked last year, but there are other relevant settings that are not mentioned, or something in the code base has changed since then:

How to set "run only at login" and "work like" with TaskScheduler in C #?

I think this approach is probably correct, but when I try it, I get a confusing error message:

Task Scheduler 2.0 (1.2) does not support setting this property. You must use InteractiveToken to run the task in the current user session.

The code I use is as follows:

    public static void ScheduleTask(string machineName, string taskName, string taskAccount, string password)
    {
        using (TaskService ts = new TaskService(machineName))
        {
            TaskDefinition td = ts.NewTask();

            td.Principal.RunLevel = TaskRunLevel.Highest;
            td.Principal.UserId = WindowsIdentity.GetCurrent().Name;
            td.Principal.LogonType = TaskLogonType.InteractiveToken;

            td.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
            td.Settings.DisallowStartIfOnBatteries = false;
            td.Settings.StopIfGoingOnBatteries = false;
            td.Settings.StartWhenAvailable = true;
            //td.Settings.RunOnlyIfLoggedOn = true;
            td.Settings.Enabled = true;
            td.Settings.Hidden = false;
            td.Settings.AllowHardTerminate = true;
            td.Settings.ExecutionTimeLimit = new TimeSpan();

            var tt = new SessionStateChangeTrigger();
            tt.StartBoundary = DateTime.Now.AddMinutes(1);
            tt.UserId = taskAccount;
            tt.StateChange = TaskSessionStateChangeType.RemoteConnect;
            tt.Repetition.Interval = TimeSpan.FromMinutes(1);
            tt.Repetition.StopAtDurationEnd = false;
            td.Triggers.Add(tt);

            td.Actions.Add("notepad.exe", "c:\\test.log");

            ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, taskAccount, password, TaskLogonType.Password, null);
        }
    }

If I run this code with a valid server, user, etc., it creates a task without a problem. If I comment on the "RunOnlyIfLoggedOn" parameter, it generates the error that I mentioned earlier. Please note that I am setting the LogonType property to TaskLogonType.InteractiveToken, so there should be something else that I am missing.

+2
source share
1 answer

Ok, there is a solution:

TaskLogonType Interactive Token. " TaskDefinition" .

RunOnlyIfLoggedOn (v1, w2k3 ..)

+1

All Articles