This project has moved and is read-only. For the latest updates, please go here.

Run as "Domain Users"

Jul 28, 2010 at 1:32 AM

Progmatically in C#, how do you set the "run as" user to "MyDomain\Domain Users"?  I can set it in the task scheduler GUI, but can't seem to get it with the task scheduler library.

When I try the code below (based on a best guess from the documentation hints), all it does is spit out a COM error message:

(98,4): Task:


private string login_user = "domainusername";
private string login_domain = "mydomain";
private string login_pass = "mypass";

TaskService ts = new TaskService();
TaskDefinition td = ts.NewTask();
td.Actions.Add(new ExecAction("C:\scripts\test.exe", "", null));

 if (login_user != string.Empty)
	if (login_domain != string.Empty)
		login_user = login_domain + @"\" + login_user;
		td.Principal.GroupId = login_domain + @"\Domain Users";
		td.Principal.GroupId = "Users";

        ts.RootFolder.RegisterTaskDefinition("test_task", td, TaskCreation.Create, login_user, login_pass, TaskLogonType.Group, "");




Any thoughts? Thanks :)

Jul 30, 2010 at 5:45 PM

You're on the right track. I think you forgot to add a trigger and that may actually be the cause of the error. If not, I was able to get "Domain Users" as the principal with the following code.

TaskService ts = new TaskService();
TaskDefinition td = ts.NewTask();
td.Triggers.Add(new TimeTrigger() { StartBoundary = DateTime.Now + TimeSpan.FromHours(1), Enabled = false });
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", "C:\\"));
ts.RootFolder.RegisterTaskDefinition("MyTask", td, TaskCreation.Create, @"MYDOMAIN\Domain Users", null, TaskLogonType.Group, null);

You don't have to set the Principal properties like GroupId as the registration will do that for you. Also, you cannot supply a password for groups.

Aug 2, 2010 at 8:19 PM

I left out the trigger just in the example code I posted.  In my app, it works and gets added as a scheduled task when I provide an actual username and password.


However, an error gets thrown when I try what you suggested:

Access is denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Aug 2, 2010 at 9:07 PM

If I run the app using the "run as administrator" option, the code appears to work as expected.

Thanks :)