因寫的調用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