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

RegisterTaskDefinition throws 0x80070005 (E_ACCESSDENIED) exception

Topics: Errors
Sep 19, 2014 at 9:16 AM
Edited Sep 19, 2014 at 10:24 AM
Hi,

I have the following scenario:
  • Windows 8, 7 and Vista
  • Computer: PC1234
  • User: John
  • Admin: Admin
My application requires admin rights, so if my app is started from John, it runs as Admin.

If run the code to add a task to the task scheduler, the task is added for Admin and not for John.

So I tried the following code to add the task for John:
using (TaskService ts = new TaskService())
            {

                var task = ts.FindTask("TEST");
                if (task != null)
                    ts.RootFolder.DeleteTask("TEST");

                                 TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = "Daily shutdown";

                    // Create a trigger that will fire the task at this time every other day
                    var now = DateTime.Now;
                    var timeSpan = TimeSpan.Parse(ConvertedValue as string);
                    var dateTime = new DateTime(now.Year, now.Month, now.Day, timeSpan.Hours, timeSpan.Minutes, 0);
                    td.Triggers.Add(new DailyTrigger { DaysInterval = 1, StartBoundary = dateTime });

                    td.Actions.Add(new ExecAction("shutdown", "/s", null));

                    td.Settings.ExecutionTimeLimit = TimeSpan.FromMinutes(15); // also tried without this line
                    td.Principal.RunLevel = TaskRunLevel.LUA; // also tried Highest
                    td.Principal.LogonType = TaskLogonType.S4U; // also tried without this line
                    td.Principal.UserId = @"PC1234\John"; // also tried without this line

                    // Register the task in the root folder
                    var folder = ts.RootFolder.CreateFolder("Testfolder"); // also tried directly to add the task to RootFolder
                    folder.RegisterTaskDefinition("TEST", td, TaskCreation.CreateOrUpdate, @"PC1234\John");
                

            }
If I remove the "PC1234\John", everything is working without an error, but the task is added for Admin. If I add the user name, I got the access denied exception.

As you can see, I tried all suggestions from this forum, to fix this (custom folder, execution time, etc.).

How can I fix this? I searched the whole forum, but all tips are not working.

Best regards,
Sascha

EDIT: I got it. With TaskLogonType.InteractiveToken it is working.
Coordinator
Sep 19, 2014 at 1:59 PM
Glad you got it. Another options is to remove the 3 lines where you set td.Principal properties and then supply all the parameters to the RegisterTaskDefinition method, including the password and the S4U logon type.