Beispiel #1
0
        public int Install()
        {
            int result = 0;

            Console.WriteLine("Start Install..");
            this.withThrowExceptionIfPermissionDeneed();

            if (isTargetTask())
            {
                throw new InvalidOperationException("Task has already been setup. Please uninstall first.");
            }

            // TODO: Registry save (Only on first run)

            // create shortcut
            //string path = AppDomain.CurrentDomain.BaseDirectory;
            string exeFullPathFileName = Process.GetCurrentProcess().MainModule.FileName;
            //Console.WriteLine($"path       : {path}");
            //Console.WriteLine($"name       : {exeFullPathFileName}");

            // create shortcut
            ShortcutCreator shortcut = new ShortcutCreator(exeFullPathFileName, "-s", ShortcutCreator.TargetSpecialFolder.CommonPrograms);

            shortcut.AppUserModelID = Program.generateDefaultAppUserModelID();
            shortcut.create();

            // create task
            using (TaskService taskService = new TaskService())
            {
                // regist task scheduler
                TimeSpan span = TimeSpan.FromHours(1);
                Task     task = taskService.Execute(exeFullPathFileName).WithArguments("-s").AtLogon().RepeatingEvery(span).AsTask(D_PREVENT_REBOOT_TASK);

                TaskDefinition definition = task.Definition;

                TaskPrincipal principal = definition.Principal;
                principal.RunLevel = TaskRunLevel.Highest;
                principal.UserId   = "SYSTEM";

                TaskRegistrationInfo info = definition.RegistrationInfo;
                info.Author      = "PreventReboot";
                info.Description = "This program prevents reboot during login by updating the ActiveTime of Windows10 on a regular basis.";

                TaskSettings settings = definition.Settings;
                settings.DisallowStartIfOnBatteries = false;
                settings.StopIfGoingOnBatteries     = false;
                settings.RunOnlyIfIdle      = false;
                settings.Hidden             = true;
                settings.Enabled            = true;
                settings.StartWhenAvailable = true;

                IdleSettings idle = settings.IdleSettings;
                idle.RestartOnIdle = false;
                idle.StopOnIdleEnd = false;

                task.RegisterChanges();
            }

            return(result);
        }
 private bool ValidateAccountForSidType(string user)
 {
     if (!TaskPrincipal.ValidateAccountForSidType(user, td.Principal.ProcessTokenSidType))
     {
         MessageBox.Show(this, EditorProperties.Resources.Error_PrincipalSidTypeInvalid, EditorProperties.Resources.TaskSchedulerName, MessageBoxButtons.OK, MessageBoxIcon.Error);
         return(false);
     }
     return(true);
 }
Beispiel #3
0
 public void Dispose()
 {
     _regInfo = null;
     _triggers = null;
     _settings = null;
     _principal = null;
     _actions = null;
     if (_v2Def != null)
         Marshal.ReleaseComObject(_v2Def);
     _v1Task = null;
 }
Beispiel #4
0
        public void ScheduleRenewTask()
        {
            string taskName = $"Lets encrypt renew {CleanFileName(_options.HostName)}";

            Log.Information($"Creating Task {taskName} with Windows Task scheduler at 9am every day.");

            DateTime now     = DateTime.UtcNow;
            DateTime runtime = new DateTime(now.Year, now.Month, now.Day, 9, 0, 0, DateTimeKind.Utc);

            string currentExec = Assembly.GetExecutingAssembly().Location;

            // Create an action that will launch the app with the renew parameters whenever the trigger fires
            string actionString = $"\"{string.Join("\" \"", Environment.GetCommandLineArgs().Skip(1))}\" --renew";

            using (TaskService taskService = new TaskService())
                using (DailyTrigger trigger = new DailyTrigger {
                    DaysInterval = 1, StartBoundary = runtime
                })
                    using (ExecAction action = new ExecAction(currentExec, actionString, Path.GetDirectoryName(currentExec)))
                        using (TaskFolder rootFolder = taskService.RootFolder)
                            using (TaskDefinition task = taskService.NewTask())
                                using (TaskRegistrationInfo reginfo = task.RegistrationInfo)
                                    using (TriggerCollection triggers = task.Triggers)
                                        using (ActionCollection actions = task.Actions)
                                            using (TaskPrincipal principal = task.Principal)
                                            {
                                                rootFolder.DeleteTask(taskName, false);

                                                reginfo.Description = $"Check for renewal of ACME certificates for {_options.HostName}.";
                                                triggers.Add(trigger);
                                                actions.Add(action);
                                                principal.RunLevel  = TaskRunLevel.Highest; // need admin
                                                principal.LogonType = TaskLogonType.ServiceAccount;
                                                principal.UserId    = "SYSTEM";

                                                rootFolder.RegisterTaskDefinition(taskName, task);
                                            }
        }
Beispiel #5
0
        public static Boolean Execute
        (
            String Target,
            String Command,
            String Domain          = "",
            String Username        = "",
            String Password        = "",
            String taskName        = "",
            String taskDescription = "",
            Boolean Onstartup      = false,
            Boolean Wakeup         = false,
            Int32 TimeFromNow      = 2,
            Boolean RunAsSystem    = false,
            String DiffDomain      = null,
            String DiffUser        = null,
            String DiffPassword    = null,
            Boolean ListJobs       = false,
            String JobToDelete     = null,
            Int32 DeleteAfter      = 10
        )
        {
            SecureString secureString = null;

            if (taskName == null)
            {
                taskName = Utils.RandomString();
            }

            if (taskDescription == null)
            {
                taskDescription = Utils.RandomString();
            }

            Logger.Print(Logger.STATUS.INFO, "Connecting to: " + Target);

            if (Domain != null && Username != null && Password != null)
            {
                String Auth = Domain + "\\" + Username;
                Logger.Print(Logger.STATUS.INFO, "Authenticating as: " + Auth + ":" + Password);
                secureString = new NetworkCredential("", Password).SecurePassword;
            }
            else
            {
                Logger.Print(Logger.STATUS.INFO, "Authenticating as: " + Environment.UserDomainName + "\\" + Environment.UserName);
            }

            Boolean Response = Manager(
                Target,
                taskName,
                taskDescription,
                Command,
                Domain,
                Username,
                secureString,
                Onstartup,
                Wakeup,
                TimeFromNow,
                RunAsSystem,
                DiffDomain,
                DiffUser,
                DiffPassword,
                ListJobs,
                JobToDelete,
                DeleteAfter
                );

            if (!Response)
            {
                return(false);
            }

            if (ListJobs || JobToDelete != null)
            {
                return(true);
            }

            using (TaskService ts = new TaskService($"\\\\{Target}", Username, Domain, Password))
            {
                Task[]  tasks   = ts.FindAllTasks(new System.Text.RegularExpressions.Regex("."), true);
                Boolean isFound = false;

                foreach (Task task in tasks)
                {
                    TaskPrincipal princ = task.Definition.Principal;
                    if (task.Name.Contains(taskName))
                    {
                        Logger.Print(Logger.STATUS.GOOD, $"Task: '{task.Name}' User: '******' Enabled: {task.Enabled} Next Run: {task.NextRunTime}");
                        isFound = true;
                        break;
                    }
                }
                if (!isFound)
                {
                    Logger.Print(Logger.STATUS.ERROR, "Task was not created.");
                }
            }
            return(true);
        }