3

I'm creating Windows Scheduled Tasks dynamically from c# using the build-in TaskService and TaskDefinition libraries.

But for some of them, we need to create then to run as a different user (Local Service or Network Service). As the tasks are created and removed dynamically we cannot edit all of them manually to change the user. We need to do it via code. Is is possible?

I've tried the following settings:

TaskDefinition.Principal.Id = "NETWORK SERVICE";
TaskDefinition.Principal.LogonType = TaskLogonType.ServiceAccount;

but this gives me the very descript error when creating the task:

System.Runtime.InteropServices.COMException: '(52,4):Task:'

Without those 2 lines, it works but creates them as the logged in user.

Cameron Castillo
  • 2,712
  • 10
  • 47
  • 77
  • 1
    Have you tried setting **UserId** property of Principal to `NT AUTHORITY\NETWORK SERVICE`? – Markus Feb 18 '19 at 12:30
  • Thanks for the suggestion. I've tried it now and it gives an error: 'System.Runtime.InteropServices.COMException: '(18,8):UserId:' Without the domain, it gives an 'E_ACCESSDENIED' error. – Cameron Castillo Feb 18 '19 at 13:30
  • Just to be certain: have you escaped the backslash, e.g. `TaskDefinition.Principal.UserId = "NT AUTHORITY\\NETWORK SERVICE";`? – Markus Feb 18 '19 at 13:31
  • Yes, I have. Without the escape char it also gives an compile error. – Cameron Castillo Feb 18 '19 at 13:35

1 Answers1

2

I've played around with the Task Scheduler stuff a bit and have replicated your problem. I believe I’ve found some things out, maybe they can help.

1. Firstly if your making Tasks in the debugger using Services Accounts, you'll want to ensure your Visual Studio or other IDE is launched as administrator to ensure you have the correct privileges to do this task.

2. I'm not sure if you do this later in your code but to make the task save and run as NETWORK SERVICE, I had to Identify Network Service as NT AUTHORITY\\NETWORKSERVICE in both the principle and on the RegisterTaskDefinition method:

TaskService tService = new TaskService();
TaskDefinition tDefinition = tService.NewTask();
tDefinition.Principal.Id = "NT AUTHORITY\\NETWORKSERVICE";
tDefinition.Principal.LogonType = TaskLogonType.ServiceAccount;
tDefinition.RegistrationInfo.Description = "Testing";

tDefinition.Triggers.Add(new DailyTrigger {DaysInterval = 2});
tDefinition.Actions.Add(new ExecAction("notepad.exe"));
tService.RootFolder.RegisterTaskDefinition(@"Test", tDefinition, TaskCreation.CreateOrUpdate, 
                                            "NT AUTHORITY\\NETWORKSERVICE", null, 
                                            TaskLogonType.ServiceAccount);

I used the above code to make a test Task that got successfully added to my scheduler as Network Service as shown below: enter image description here

I'm guessing that one or both of the above points may have stopped the task from being added, hope that helps

Jacob JA Shanks
  • 370
  • 1
  • 13