c# : Create windows scheduled task as a different

2019-07-20 11:36发布

问题:

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.

回答1:

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:

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