How to set security options

Feb 18, 2011 at 6:16 PM

Under Security Options in the Task Scheduler GUI, it says, "When running the task, use the following user account," and by default, that field is populated with the domain and user account of the person creating the task. In the GUI, I can click on the button "Change User or Group..." to change that field. But how can I do this programmatically?

Coordinator
Feb 22, 2011 at 5:38 PM
Edited Feb 22, 2011 at 5:41 PM

That UI element is connected to the TaskDefinition.Principal.UserId or TaskDescriptor.Principal.GroupId property. See the examples under the Documentation tab for how to set that.

Feb 22, 2011 at 7:33 PM

I've tried using the properties you suggest, but it doesn't seem to work for me. Here is the code I'm using for setting up and creating my task:

TaskService ts = new TaskService();
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Run " + taskName + " at logon";
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.Principal.GroupId = "BUILTIN";
td.Principal.UserId = "Administrators";
LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
td.Actions.Add(new ExecAction(taskAppLocation, null, null));
ts.RootFolder.RegisterTaskDefinition(taskName, td);

I want the task to run under the Administrators account because I want the task to run for all users and administrators, regardless of which administrator created the task. It seems that in Windows 7, Task Scheduler won't run a task created by one administrator if another administrator is logged in, but you can get around this behavior by setting the security option to run the task under the BUILTIN\Administrators account. I just can't seem to set that setting through the managed wrapper. I implemented the code as written above (following your guidance as I understand it), but it doesn't change the security option setting from the default. Am I missing something? Perhaps one of my other settings is interfering?

Thanks for your help.

Coordinator
Feb 23, 2011 at 1:30 AM

You are trying to use the Principal class incorrectly. The GroupId property is to be used when the LogonType property is set to TaskLogonType.Group. The UserId property is to be used for all other logon types. The corrected code would be:

TaskService ts = new TaskService();
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Run " + taskName + " at logon";
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.Principal.GroupId = @"BUILTIN\Administrators";
td.Principal.LogonType = TaskLogonType.Group;
td.Triggers.Add(new LogonTrigger());
td.Actions.Add(new ExecAction(taskAppLocation, null, null));
ts.RootFolder.RegisterTaskDefinition(taskName, td);
Feb 23, 2011 at 8:57 PM

Yep, that did it. Thanks for correcting my understanding of how to use the GroupId and UserId properties.