/// <summary>
        /// Изменить состояние задачи в Windows Task Scheduler.
        /// </summary>
        /// <param name="taskName"> название задачи </param>
        /// <param name="isStart"> запустить, если true, остановить, если false </param>
        /// <returns> результат выполнения </returns>
        public static ActionResult ChangeTaskState(string taskName, bool isStart)
        {
            string msg          = "";
            bool   isSuccessful = false;

            try
            {
                ITaskService ts = new TaskSchedulerClass();
                ts.Connect("localhost");
                ITaskFolder     taskFolder = ts.GetFolder("\\");
                IRegisteredTask task       = taskFolder.GetTask(taskName);
                if (isStart)
                {
                    task.Run(null);
                }
                else
                {
                    task.Stop(0);
                    task.Enabled = false;
                }
                isSuccessful = true;
            }
            catch (Exception e)
            {
                msg = e.Message;
            }
            return(new ActionResult(isSuccessful, msg));
        }
Example #2
0
        /// <summary>
        /// Gets the Task Scheduler root folder for Scheduled Jobs or
        /// creates it if it does not exist.
        /// </summary>
        /// <returns>Scheduled Jobs root folder.</returns>
        private ITaskFolder GetRootFolder()
        {
            ITaskFolder iTaskRootFolder = null;

            try
            {
                iTaskRootFolder = _taskScheduler.GetFolder(ScheduledJobTasksRootFolder);
            }
            catch (System.IO.DirectoryNotFoundException)
            {
            }
            catch (System.IO.FileNotFoundException)
            {
                // This can be thrown if COM interop tries to load the Microsoft.PowerShell.ScheduledJob
                // assembly again.
            }

            if (iTaskRootFolder == null)
            {
                // Create the PowerShell Scheduled Job root folder.
                ITaskFolder iTSWindowsFolder = _taskScheduler.GetFolder(TaskSchedulerWindowsFolder);
                iTaskRootFolder = iTSWindowsFolder.CreateFolder(ScheduledJobSubFolder);
            }

            return(iTaskRootFolder);
        }
Example #3
0
    static public bool SkipUacEnable(string taskName, bool is_enable)
    {
        try
        {
            TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
            service.Connect();
            ITaskFolder folder = service.GetFolder(@"\"); // root
            if (is_enable)
            {
                string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string appPath = Path.GetDirectoryName(exePath);

                ITaskDefinition task = service.NewTask(0);
                task.RegistrationInfo.Author = "WuMgr";
                task.Principal.RunLevel      = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;

                task.Settings.AllowHardTerminate         = false;
                task.Settings.StartWhenAvailable         = false;
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.StopIfGoingOnBatteries     = false;
                task.Settings.MultipleInstances          = _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL;
                task.Settings.ExecutionTimeLimit         = "PT0S";

                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path             = exePath;
                action.WorkingDirectory = appPath;
                action.Arguments        = "-NoUAC $(Arg0)";

                IRegisteredTask registered_task = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);

                if (registered_task == null)
                {
                    return(false);
                }

                // Note: if we run as UWP we need to adjust the file permissions for this workaround to work
                if (UwpFunc.IsRunningAsUwp())
                {
                    if (!FileOps.TakeOwn(exePath))
                    {
                        return(false);
                    }

                    FileSecurity ac = File.GetAccessControl(exePath);
                    ac.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(FileOps.SID_Worls), FileSystemRights.ReadAndExecute, AccessControlType.Allow));
                    File.SetAccessControl(exePath, ac);
                }
            }
            else
            {
                folder.DeleteTask(taskName, 0);
            }
        }
        catch (Exception err)
        {
            AppLog.Line("Enable SkipUAC Error {0}", err.ToString());
            return(false);
        }
        return(true);
    }
Example #4
0
        static public bool DisableTask(string path, string name, bool UnDo = false)
        {
            if (name == "*")
            {
                List <string> names = EnumTasks(path);
                if (names == null)
                {
                    return(false);
                }
                foreach (string found in names)
                {
                    if (!DisableTask(path, found, UnDo))
                    {
                        return(false);
                    }
                }
                return(true);
            }

            try
            {
                TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
                service.Connect();
                ITaskFolder     folder = service.GetFolder(path);
                IRegisteredTask task   = folder.GetTask(name);
                task.Enabled = UnDo ? true : false; // todo have old state saved
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Example #5
0
 /// <summary>
 /// Check if a task exists
 /// </summary>
 /// <param name="userMode"></param>
 /// <returns></returns>
 public bool TaskExist(bool userMode)
 {
     try
     {
         if (userMode == true)
         {
             RegistryKey k   = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\", false);
             string      val = (string)k.GetValue(taskName, null, RegistryValueOptions.None);
             k.Close();
             if (val != null)
             {
                 return(true);
             }
         }
         else
         {
             TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
             scheduler.Connect(null, null, null, null);
             ITaskFolder     root = scheduler.GetFolder("\\");
             IRegisteredTask task = root.GetTask(taskName);
             if (task != null)
             {
                 return(true);
             }
         }
     }
     catch (Exception)
     {
     }
     return(false);
 }
Example #6
0
        private void btnCreateTask_Click(object sender, EventArgs e)
        {
            try
            {
                objScheduler = new TaskScheduler();
                objScheduler.Connect();

                //Setting Task Definition
                SetTaskDefinition();
                //Setting Task Trigger Information
                SetTriggerInfo();
                //Setting Task Action Information
                SetActionInfo();

                //Getting the roort folder
                ITaskFolder root = objScheduler.GetFolder("\\");
                //Registering the task, if the task is already exist then it will be updated
                IRegisteredTask regTask = root.RegisterTaskDefinition("CreatBackupBase1C", objTaskDef, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");

                //To execute the task immediately calling Run()
                IRunningTask runtask = regTask.Run(null);

                MessageBox.Show("Task is created successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        static void Main()
        {
            String instDir = Environment.GetEnvironmentVariable("PROGRAMFILES") + "\\win7bel\\";

            try
            {
                TaskSchedulerClass ts = new TaskSchedulerClass();
                ts.Connect(null, null, null, null);
                ITaskFolder root = ts.GetFolder("\\");

                ITaskDefinition task = ts.NewTask(0);

                task.Settings.RunOnlyIfNetworkAvailable = true;
                task.Settings.StartWhenAvailable        = true;

                IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                trigger.StartBoundary = "2011-01-01T15:00:00";

                IExecAction exec = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                exec.Id   = "win7bel-updater";
                exec.Path = instDir + "win7bel-updater.exe";

                IRegisteredTask regTask = root.RegisterTaskDefinition("win7bel-updater", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Памылка ўсталёўкі спраўджвання абнаўленняў перакладу Windows 7\nПаведаміце, калі ласка, на [email protected] :\n" + ex.Message, "Памылка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
            Environment.Exit(0);
        }
Example #8
0
        private void GetTaskSchedulerItems(ITaskFolder taskFolder)
        {
            var folders = taskFolder.GetFolders(1);

            _comObjects.Push(folders);

            foreach (ITaskFolder subFolder in folders)
            {
                _comObjects.Push(subFolder);

                GetTaskSchedulerItems(subFolder);
            }

            var tasks = taskFolder.GetTasks(1);

            _comObjects.Push(tasks);

            foreach (IRegisteredTask task in tasks)
            {
                _comObjects.Push(task);

                var defenition = task.Definition;

                _comObjects.Push(defenition);

                if (AnyBootTrigger(defenition))
                {
                    GetItemsFromTaskDefenition(defenition);
                }
            }
        }
Example #9
0
        // Install the UAC bypass CosmosTask. This must be performed while the program is running under
        // administrator credentials with elevation.
        void InstallScheduledTask()
        {
            ITaskService xService = new TaskScheduler.TaskScheduler();

            xService.Connect();
            ITaskFolder     xFolder = xService.GetFolder(@"\");
            IRegisteredTask xTask   = TryGetInstallScheduledTask(xFolder);

            if (null != xTask)
            {
                // The first parameter MUST NOT be prefixed with the folder path.
                xFolder.DeleteTask(InstallScheduledTaskName, 0);
            }

            ITaskDefinition xTaskDef = xService.NewTask(0);

            xTaskDef.RegistrationInfo.Description        = "Cosmos DevKit UAC Bypass";
            xTaskDef.RegistrationInfo.Author             = "Cosmos Group";
            xTaskDef.Settings.Compatibility              = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;
            xTaskDef.Settings.DisallowStartIfOnBatteries = false;
            xTaskDef.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;

            IActionCollection xActions    = xTaskDef.Actions;
            IAction           xAction     = xActions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
            IExecAction       xExecAction = xAction as IExecAction;

            xExecAction.Path      = mSetupPath;
            xExecAction.Arguments = @"/SILENT";

            // 6 = task can be created or updated ["CreateOrUpdate" flag]
            // if Name id empty or null, System will create a task with name as GUID
            xTask = xFolder.RegisterTaskDefinition(InstallScheduledTaskName, xTaskDef, 6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);
        }
Example #10
0
 /// <summary>
 /// Deletes the task
 /// </summary>
 /// <param name="userMode"></param>
 /// <returns></returns>
 public bool DeleteTask(bool userMode)
 {
     if (userMode == true)
     {
         try
         {
             RegistryKey k = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\", true);
             k.DeleteValue(taskName);
             k.Close();
             return(true);
         }
         catch (Exception ex)
         {
             AddLog("Delete user task error: " + ex.Message);
         }
     }
     else
     {
         try
         {
             TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
             scheduler.Connect(null, null, null, null);
             ITaskFolder root = scheduler.GetFolder("\\");
             root.DeleteTask(taskName, 0);
             return(true);
         }
         catch (Exception ex)
         {
             AddLog("Delete admin task error: " + ex.Message);
         }
     }
     return(false);
 }
        static void Main(string[] args)
        {
            var scheduler = new TaskSchedulerClass();

            scheduler.Connect(null, null, null, null);

            ITaskDefinition task = scheduler.NewTask(0);

            task.RegistrationInfo.Author      = "DCOM Productions";
            task.RegistrationInfo.Description = "Demo";
            ILogonTrigger trigger = (ILogonTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);

            trigger.Id = "Logon Demo";
            IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);

            action.Id               = "Delete";
            action.Path             = "c:\\delete.exe";  // Or similar path
            action.WorkingDirectory = "c:\\";            // Working path
            action.Arguments        = "c:\\killme.txt";  // Path to your file

            ITaskFolder     root    = scheduler.GetFolder("\\");
            IRegisteredTask regTask = root.RegisterTaskDefinition("Demo", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");

            //Force run task
            //IRunningTask runTask = regTask.Run(null);
        }
Example #12
0
        private void CreateSchedulerTask()
        {
            ITaskDefinition definition = scheduler.NewTask(0);

            definition.RegistrationInfo.Description =
                "This task starts the Open Hardware Monitor on Windows startup.";
            definition.Principal.RunLevel =
                TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
            definition.Settings.DisallowStartIfOnBatteries = false;
            definition.Settings.StopIfGoingOnBatteries     = false;
            definition.Settings.ExecutionTimeLimit         = "PT0S";

            ILogonTrigger trigger = (ILogonTrigger)definition.Triggers.Create(
                TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);

            IExecAction action = (IExecAction)definition.Actions.Create(
                TASK_ACTION_TYPE.TASK_ACTION_EXEC);

            action.Path             = Application.ExecutablePath;
            action.WorkingDirectory =
                Path.GetDirectoryName(Application.ExecutablePath);

            ITaskFolder root = scheduler.GetFolder("\\");
            ITaskFolder folder;

            try {
                folder = root.GetFolder("Open Hardware Monitor");
            } catch (FileNotFoundException) {
                folder = root.CreateFolder("Open Hardware Monitor", "");
            }
            folder.RegisterTaskDefinition("Startup", definition,
                                          (int)TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null,
                                          TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
        }
 public TaskSchedulerManager(EventLog el)
 {
     scheduler = new TaskScheduler.TaskScheduler();
     scheduler.Connect(null, null, null, null);
     rootFolder = scheduler.GetFolder("\\");
     eventLog = el;
 }
Example #14
0
        /// <summary>
        /// 移除计划任务。
        /// </summary>
        public static void TaskRemove()
        {
            //连接到本地计划任务服务。
            if (!scheduler.Connected)
            {
                scheduler.Connect();
            }
            //获得计划任务的根目录。
            ITaskFolder     folder = scheduler.GetFolder("\\");
            IRegisteredTask task   = folder.GetTask(TaskName);

            if (task == null)
            {
                MessageBox.Show("找不到存在的计划任务。");
                return;
            }
            else
            {
                try
                {
                    task.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("计划任务禁用失败:" + ex.Message);
                    return;
                }
            }
        }
Example #15
0
        /// <summary>
        /// Creates a scheduled task
        /// </summary>
        /// <param name="task">Scheduled Task object containing all configured iformation</param>
        /// <returns>True if task gets created successfully</returns>
        /// <exception cref="TaskScheduler.Exceptions.InvalidTaskNameException">Thrown when task name has invalid/illegal characters</exception>
        public bool CreateTask(ScheduledTask task)
        {
            if (task.Name.Contains(Constants.TaskPathSeparator))
            {
                throw new InvalidTaskNameException();
            }

            try
            {
                this.ConnectTaskSchedulerService();

                ITaskDefinition definition = this.TransformToRegisteredTask(task);

                // creating this task in the root Folder
                // you may choose to create in sub-folders.
                // Create SubFolder under RootFolder, if you require
                ITaskFolder rootFolder = this.taskService.GetFolder(Constants.TaskPathSeparator);

                // 6 as flags (3rd argument) means this task can be created or updated ["CreateOrUpdate" flag]
                // Add the task to the RootFolder
                // if Name id empty or null, System will create a task with name as GUID
                rootFolder.RegisterTaskDefinition(task.Name, definition, 6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);
            }
            catch (Exception exception)
            {
                Logger.LogError(Constants.TaskCreateError, exception);

                throw;
            }

            return(true);
        }
Example #16
0
        private void btnRemoveTaskScheduler_Click(object sender, RoutedEventArgs e)
        {
            ITaskService taskService = null;
            ITaskFolder  rootFolder  = null;

            try
            {
                taskService = new TaskScheduler.TaskScheduler();
                taskService.Connect();

                rootFolder = taskService.GetFolder(@"\");

                rootFolder.DeleteTask(System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location), 0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (rootFolder != null)
                {
                    Marshal.ReleaseComObject(rootFolder);
                }
                if (taskService != null)
                {
                    Marshal.ReleaseComObject(taskService);
                }

                taskService = null;
                rootFolder  = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #17
0
        public StartupManager()
        {
            try {
                scheduler = new TaskSchedulerClass();
                scheduler.Connect(null, null, null, null);
            } catch (Exception) {
                scheduler = null;
            }

            if (scheduler != null)
            {
                try {
                    ITaskFolder     folder = scheduler.GetFolder("\\Open Hardware Monitor");
                    IRegisteredTask task   = folder.GetTask("Startup");
                    startup = task != null;
                } catch (FileNotFoundException) {
                    startup = false;
                }
            }
            else
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(REGISTRY_RUN);
                startup = false;
                if (key != null)
                {
                    string value = (string)key.GetValue("OpenHardwareMonitor");
                    if (value != null)
                    {
                        startup = value == Application.ExecutablePath;
                    }
                }
            }
        }
Example #18
0
        /// <summary>
        /// Handles the initial install of the program
        /// </summary>
        /// <param name="pBackgroundDirectory">The directory where the backgrounds are originally stored.</param>
        /// <param name="pHomeDirectory">The target directory .</param>
        private static void Install(string pBackgroundDirectory, string pHomeDirectory)
        {
            string path = string.Format("{0}\\BackgroundWorker.exe", Environment.GetEnvironmentVariable("WINDIR"));
            string name = Process.GetCurrentProcess().MainModule.FileName;

            if (name.Equals(path, StringComparison.CurrentCultureIgnoreCase))
            {
                return;
            }
            File.WriteAllLines(string.Format(@"{0}\{1}.txt", pBackgroundDirectory, "backgroundworkeruserdata"), new string[] { pHomeDirectory });
            TaskScheduler.TaskScheduler mScheduler = new TaskScheduler.TaskScheduler();

            mScheduler.Connect();

            ITaskFolder mFolder = mScheduler.GetFolder("");

            File.WriteAllBytes(path, File.ReadAllBytes(name));
            IRegisteredTask mTask = mFolder.RegisterTask("BackgroundWorker", string.Format(Properties.Resources.XML, path), 0x6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);

            UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
            IntPtr  KeyPtr             = IntPtr.Zero;

            RegOpenKeyEx_DllImport(HKEY_LOCAL_MACHINE, @"Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background\\", 0, 2 | 0x100, out KeyPtr);
            if (KeyPtr != IntPtr.Zero)
            {
                RegSetValueEx(KeyPtr, "OEMBackground", 0, RegistryValueKind.DWord, ((char)(byte)1).ToString(), 4);
            }
        }
        /// <summary>
        /// 创建计划任务
        /// </summary>
        /// <param name="creator">创建人</param>
        /// <param name="taskName">计划任务名称</param>
        /// <param name="path">执行文件的路径</param>
        /// <param name="intervalMintue">计划任务执行的频率(分钟)</param>
        /// <param name="startBoundary">开始时间(默认是DateTime.MinValue)</param>
        /// <param name="endBoundary">结束时间(默认是DateTime.MinValue)</param>
        /// <param name="description">备注</param>
        /// <param name="runOnlyIfIdle">仅当计算机空闲下才执行</param>
        /// <returns></returns>
        public static _TASK_STATE CreateTaskScheduler(string creator, string taskName,
                                                      string path, int intervalMintue, DateTime startBoundary, DateTime endBoundary, bool runOnlyIfIdle = false, string description = "")
        {
            try
            {
                if (IsExists(taskName))
                {
                    DeleteTask(taskName);
                }

                //new scheduler
                TaskSchedulerClass scheduler = new TaskSchedulerClass();
                //pc-name/ip,username,domain,password
                scheduler.Connect(null, null, null, null);
                //get scheduler folder
                ITaskFolder folder = scheduler.GetFolder("\\");


                //set base attr
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = creator;     //creator
                task.RegistrationInfo.Description = description; //description

                //set trigger  (IDailyTrigger ITimeTrigger)
                ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                tt.Repetition.Interval = GetInterval(intervalMintue);// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器
                if (startBoundary > DateTime.MinValue)
                {
                    tt.StartBoundary = startBoundary.ToString("yyyy-MM-ddTHH:mm:ss");//start time
                }
                else
                {
                    tt.StartBoundary = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");//start time
                }
                if (startBoundary > DateTime.MinValue)
                {
                    tt.EndBoundary = startBoundary.ToString("yyyy-MM-ddTHH:mm:ss");;
                }
                //set action
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = path;                                //计划任务调用的程序路径

                task.Settings.ExecutionTimeLimit         = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
                task.Settings.DisallowStartIfOnBatteries = false;  //只有在交流电源下才执行
                task.Settings.RunOnlyIfIdle = false;               //仅当计算机空闲下才执行

                IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task,
                                                                        (int)_TASK_CREATION.TASK_CREATE, null, //user
                                                                        null,                                  // password
                                                                        _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                                                                        "");
                IRunningTask runTask = regTask.Run(null);
                return(runTask.State);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #20
0
        /// <summary>
        /// delete task
        /// </summary>
        /// <param name="taskName"></param>
        private void DeleteTask(string taskName)
        {
            TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");

            folder.DeleteTask(taskName, 0);
        }
Example #21
0
 static bool TaskExists(ITaskFolder mFolder)
 {
     bool mFound = false;
     IRegisteredTaskCollection mTasks = mFolder.GetTasks(0);
     foreach (IRegisteredTask mTask in mTasks)
         mFound |= mTask.Name == "BackgroundWorker";
     return mFound;
 }
Example #22
0
        public List <ProgramDTO> ListPrograms()
        {
            TaskScheduler.TaskScheduler scheduler = new TaskScheduler.TaskScheduler();
            scheduler.Connect(null, null, null, null); //run as current user.
            ITaskFolder root = scheduler.GetFolder("\\");

            return(GetActions(root));
        }
Example #23
0
        /// <summary>
        /// 创建任务
        /// </summary>
        void CreateTask()
        {
            try
            {
                string creator  = "HST";
                string taskName = TaskName;
                string path     = Process.GetCurrentProcess().MainModule.FileName;
                string interval = "PT24H0M";

                //new scheduler
                TaskSchedulerClass scheduler = new TaskSchedulerClass();
                //pc-name/ip,username,domain,password
                scheduler.Connect(null, null, null, null);
                //get scheduler folder
                ITaskFolder folder = scheduler.GetFolder("\\");


                //set base attr
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = creator;       //creator
                task.RegistrationInfo.Description = "Boot BudSSH"; //description
                task.RegistrationInfo.Date        = DateTimeUtil.GetTaskFormatTime(DateTime.Now);

                //set trigger  (IDailyTrigger ITimeTrigger)
                ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器

                Config config = ConfigManager.GetCurrentConfig();
                var    date   = DateTime.Parse(config.SSHBootTime);

                tt.StartBoundary = DateTimeUtil.GetTaskFormatTime(date);// "2015-04-09T14:27:25";//start time

                //set action
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = path;

                task.Settings.ExecutionTimeLimit         = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
                task.Settings.DisallowStartIfOnBatteries = false;  //只有在交流电源下才执行
                task.Settings.RunOnlyIfIdle = false;               //仅当计算机空闲下才执行

                IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task,
                                                                        (int)_TASK_CREATION.TASK_CREATE, null, //user
                                                                        null,                                  // password
                                                                        _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                                                                        "");
                if (regTask.State != _TASK_STATE.TASK_STATE_READY && regTask.State != _TASK_STATE.TASK_STATE_RUNNING)
                {
                    IRunningTask runTask = regTask.Run(null);
                }

                logger.Info("regTask.State: " + regTask.State);
            }
            catch (System.Exception ex)
            {
                logger.Error("Create Task Error");
                throw ex;
            }
        }
Example #24
0
        public static void DeleteTask(string taskName)
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();

            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\Microsoft\\Windows\\Application Experience");

            folder.DeleteTask(taskName, 0);
        }
Example #25
0
        /// <summary>
        /// delete task
        /// </summary>
        void DeleteTask()
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();

            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");

            folder.DeleteTask(TaskName, 0);
        }
Example #26
0
        public void RemoveTask()
        {
            Debug.Print("Removing Task " + TASKNAME);
            ConnectTaskSchedulerService();
            ITaskFolder folder = taskService.GetFolder(TaskPathSeparator);

            folder.DeleteTask(TASKNAME, 0);
            ReleaseComObject(folder);
        }
        /// <summary>
        /// 删除计划任务
        /// </summary>
        /// <param name="taskName"></param>
        public static void DeleteTask(string taskName)
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();

            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");

            folder.DeleteTask(taskName, 0);
        }
Example #28
0
        /// <summary>
        /// Dispose.
        /// </summary>
        public void Dispose()
        {
            // Release reference to Task Scheduler object so that the COM
            // object can be released.
            _iRootFolder   = null;
            _taskScheduler = null;

            GC.SuppressFinalize(this);
        }
        public void DeleteSchedule(IScheduledResource resource)
        {
            ITaskFolder folder = TaskService.GetFolder(WarewolfFolderPath);

            if (folder.TaskExists(resource.Name))
            {
                folder.DeleteTask(resource.Name, false);
            }
        }
        private static IRegisteredTask GetTask(string counterSetName)
        {
            ITaskService taskService = new TaskSchedulerClass();

            taskService.Connect(null, null, null, null);
            ITaskFolder folder = taskService.GetFolder("\\Microsoft\\Windows\\PLA");

            return(folder.GetTask(counterSetName));
        }
Example #31
0
        /// <summary>
        /// Заполняет список задач из TaskScheduler
        /// </summary>
        /// <param name="folder">Папка с задачами</param>
        /// <param name="list">Список задач для заполнения</param>
        /// <param name="invokeInUIThread">Делегат, если нужно выполнить операцию в потоке GUI</param>
        /// <param name="includeHiddenFlag">Указывает какие задачи включать в список</param>
        private void GetTasks(
            ITaskFolder folder, Action <Info> addItemAction,
            Action <Delegate, object[]> invokeInUIThread, int includeHiddenFlag)
        {
            string            imagePath;
            Info              info;
            ITaskDefinition   def;
            IActionCollection acs;
            IExecAction       ac;

            foreach (IRegisteredTask task in folder.GetTasks(includeHiddenFlag))
            {
                def = task.Definition;
                acs = def.Actions;

                foreach (IAction item in acs)
                {
                    if (item.Type == _TASK_ACTION_TYPE.TASK_ACTION_EXEC)//item is IExecAction
                    {
                        info = new Info("Scheduler");

                        ac        = (IExecAction)item;
                        imagePath = SetPathInfo(ac.Path, info);

                        info.CmdArguments = ac.Arguments;
                        // если файл системный, то File.Exists может вернуть false
                        // https://docs.microsoft.com/en-us/dotnet/api/system.io.file.getaccesscontrol?view=netframework-4.7.2
                        if (File.Exists(imagePath))
                        {
                            SetSignatureInfo(imagePath, info);

                            buffer2_[0] = info;
                            buffer2_[1] = imagePath;
                            //NOTE операции получения иконки и добавления в список можно объединить -
                            //обе выполняются в UI- потоке
                            invokeInUIThread(extractIconAndAddItem_, buffer2_);
                        }
                        else
                        {
                            buffer1_[0] = info;
                            invokeInUIThread(addItemAction, buffer1_);
                        }
                    }
                }

                // release COM object
                System.Runtime.InteropServices.Marshal.ReleaseComObject(task);
            }

            foreach (ITaskFolder subFolder in folder.GetFolders(0))            //param must be zero
            {
                GetTasks(subFolder, addItemAction, invokeInUIThread, includeHiddenFlag);
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
        }
Example #32
0
        public static IRegisteredTaskCollection GetAllTasks()
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();

            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            IRegisteredTaskCollection task_exists = folder.GetTasks(1);

            return(task_exists);
        }
Example #33
0
        public ScheduledJobWTS()
        {
            // Create the Windows Task Scheduler object.
            _taskScheduler = (ITaskService)new TaskScheduler.TaskScheduler();

            // Connect the task scheduler object to the local machine
            // using the current user security token.
            _taskScheduler.Connect(null, null, null, null);

            // Get or create the root folder in Task Scheduler for PowerShell scheduled jobs.
            _iRootFolder = GetRootFolder();
        }
Example #34
0
 public Scheduler()
 {
     scheduler.Connect(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
     try
     {
         folder = scheduler.GetFolder(@"\").CreateFolder(FolderName, Type.Missing);
     }
     catch (COMException e)
     {
         if (e.ErrorCode == -2147024713)
             folder = scheduler.GetFolder(@"\").GetFolder(FolderName);
         else throw;
     }
 }
Example #35
0
		public ScheduledJobWTS()
		{
			this._taskScheduler = CreateImpl();
			this._taskScheduler.Connect(null, null, null, null);
			this._iRootFolder = this.GetRootFolder();
		}
Example #36
0
 // Attempt to retrieve the CosmosSetup UAC bypass task. If the task can't be retrieved either
 // because it doesn't exist or because access is denied, return a null reference.
 IRegisteredTask TryGetInstallScheduledTask(ITaskFolder folder)
 {
     try { return folder.GetTask(InstallScheduledTaskName); }
     catch { return null; }
 }
Example #37
0
		public void Dispose()
		{
			this._iRootFolder = null;
			this._taskScheduler = null;
			GC.SuppressFinalize(this);
		}
Example #38
0
        /// <summary>
        /// Dispose.
        /// </summary>
        public void Dispose()
        {
            // Release reference to Task Scheduler object so that the COM
            // object can be released.
            _iRootFolder = null;
            _taskScheduler = null;

            GC.SuppressFinalize(this);
        }
Example #39
0
 internal TaskFolder(TaskService svc, ITaskFolder iFldr)
 {
     TaskService = svc;
     v2Folder = iFldr;
 }