在windows下,命令调用schtasks.exe 创建与删除计划任务实现程序自启动
命令
C#
public sealed class Command
{
public static string Windows(string arg, string[] commands)
{
return Execute("cmd.exe", arg, commands);
}
public static string Execute(string fileName, string arg, string[] commands)
{
Process proc = new Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = fileName;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Arguments = arg;
proc.StartInfo.Verb = "runas";
proc.Start();
if (commands.Length > 0)
{
for (int i = 0; i < commands.Length; i++)
{
proc.StandardInput.WriteLine(commands[i]);
}
}
proc.StandardInput.AutoFlush = true;
proc.StandardInput.WriteLine("exit");
string output = proc.StandardOutput.ReadToEnd();
proc.StandardError.ReadToEnd();
proc.WaitForExit();
proc.Close();
proc.Dispose();
return output;
}
}
创建
C#
string str = "schtasks.exe /create /tn \"任务名\" /rl highest /sc ONSTART /delay 0000:30 /tr \"可执行程序绝对路径\" /f"
Command.Windows("schtasks.exe", new string[] {str});
删除
C#
string str = "schtasks /delete /TN \"任务名\" /f";
Command.Windows("schtasks.exe", new string[] {str});