dahall / TaskScheduler

Provides a .NET wrapper for the Windows Task Scheduler. It aggregates the multiple versions, provides an editor and allows for localization.
MIT License
1.2k stars 191 forks source link

problem with Task when starting from a service #973

Closed Slavok47 closed 1 year ago

Slavok47 commented 1 year ago

I can not figure out the launch and services, tell me what the problem is

using (TaskService service = new TaskService())
            {
                string taskName = "YourScheduled";              
                    var task = service.NewTask();
                    task.RegistrationInfo.Description = "YourScheduledTaskDescription";
                    task.RegistrationInfo.Author = "YourScheduled";
                    task.Actions.Add(new ExecAction(@"C:\Windows\notepad.exe"));
                    TaskService.Instance.RootFolder.RegisterTaskDefinition(taskName, task).Run(); 
            }

when using WinForm everything is fine, the service is used from LocalSystem

dahall commented 1 year ago

Check info at #494

Slavok47 commented 1 year ago

I don't think it's a permissions issue, the error is in the line TaskService service = new TaskService();

I tried to process it

        try
            {
               TaskService service = new TaskService();
            }
            catch (Exception x)
            {
                output log              
            }

but it doesn't work, I don't even understand why

Slavok47 commented 1 year ago

The problem is solved, now the task is created, but on behalf of the system, it needs to be run on behalf of the user logged into the system

Slavok47 commented 1 year ago

Problem solved, everything works, I don't know how much is correct

ManagementObjectSearcher searcher_User = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
                    ManagementObjectCollection collection = searcher_User.Get();
                    string userName = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
                    TaskService.Instance.RootFolder.RegisterTaskDefinition(taskName, task, TaskCreation.CreateOrUpdate, userName, null, TaskLogonType.None).Run();