using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
string res;
int ret;
string taskName = "HelloTask";
string cmd;
// 查询命令 schtasks /query /tn HelloTask
cmd = "schtasks /query"
+ " /tn " + taskName // タスク名
;
Console.WriteLine("cmd=[{0}]", cmd);
ret = consoleExecute(cmd, out res);
Console.WriteLine("ret=[{0}]", ret);
if (ret == 1)
{
// 执行命令
cmd = "schtasks /create"
+ " /tn " + taskName
+ " /tr C:\\Temp\\HelloTask.exe"
+ " /sc MINUTE" // 执行间隔
;
Console.WriteLine("cmd=[{0}]", cmd);
}
else
{
// 删除任务
cmd = "schtasks /delete"
+ " /tn " + taskName
+ " /f"
;
Console.WriteLine("cmd=[{0}]", cmd);
}
ret = consoleExecute(cmd, out res);
Console.WriteLine("ret=[{0}]", ret);
//键盘敲击任意键后退出
Console.ReadKey();
}
private static int consoleExecute(string cmd
, out string res
)
{
//启动进程的信息
System.Diagnostics.ProcessStartInfo psi
= new System.Diagnostics.ProcessStartInfo();
//C:\WINDOWS\system32\cmd.exe
psi.FileName
= System.Environment
.GetEnvironmentVariable("ComSpec");
Console.WriteLine(psi.FileName);
// 该值指示应用程序的输入是否从 Process.StandardInput 流中读取。
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
// 是否在新窗口中启动该进程的值
psi.CreateNoWindow =true ;
// 执行命令
psi.Arguments = @"/c " + cmd;
Console.WriteLine(psi.Arguments);
// 执行
System.Diagnostics.Process p
= System.Diagnostics.Process.Start(psi);
// 出力を読み取る
res = p.StandardOutput.ReadToEnd();
Console.WriteLine(res);
// 等待完成
p.WaitForExit();
Console.WriteLine(p.ExitCode);
return (p.ExitCode);
}
}
}