C#建立任務計劃

來源:互聯網
上載者:User

標籤:

因寫的調用DiskPart程式是要用管理員身份啟動並執行,這樣每次開機檢查都彈個框出來確認肯定不行。搜了下,似乎也只是使用工作排程器運行來繞過UAC提升許可權比較靠譜,網上的都是添加到電腦啟動的,不是指定的使用者登入到案頭後啟動的,於是寫了下面這段來自己添加到任務計劃裡啟動:

/// <summary>
/// create task
/// </summary>
/// 需先添加引用TaskScheduler
/// <param name="creator"></param>
/// <param name="taskName"></param>
/// <param name="path"></param>
/// <returns>state</returns>
public static _TASK_STATE CreateLogonTaskScheduler(string creator, string taskName, string path)
{
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 = "描述資訊";//描述
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);
return runTask.State;

}
catch (Exception ex)
{
throw ex;
}

}

 

參考:

使用C#建立計劃任務(How to create a Task Scheduler use C# )
http://www.cnblogs.com/tonge/p/4410066.html
Security Contexts for Tasks
https://msdn.microsoft.com/en-us/library/windows/desktop/aa382140(v=vs.85).aspx

C#建立任務計劃

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.