C# start a scheduled task

微笑、不失礼 提交于 2019-11-30 03:40:06

问题


I'm trying to write a simple form in c# that will run a scheduled task one some computers. Whet I have so far is:

private void button_Click(object sender, EventArgs e)
    {
        try
        {

            for (int i = 0; i < num_of_computers; i++)
            {
                string line;
                line = (" /run /tn myTask /s " + _ReplacerObj.MyComputers[i] + " /u user s /p password");
                proc.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
                proc.FileName = @"C:\WINDOWS\SYSTEM32\schtasks.exe";
                proc.Arguments = line;
                Process.Start(proc);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Error Message!");
        }

For some reason this doesn't work (IE - the scheduled task didn't start). I tried running from cmd this:

c:\windows\system32\schtasks.exe /run /tn myTask /s myIp /u user /p password

and it worked fine. Any suggestions? THANKS!


回答1:


I suggest using one of the .NET wrappers for the task scheduler.

I have used this one in the past to good effect.




回答2:


using Microsoft.Win32.TaskScheduler;

using (TaskService tasksrvc = new TaskService(@"\\" + servername, username, domain, password, true))
{       
    Task task = tasksrvc.FindTask(taskSchedulerName);
    task.Run();
}   



回答3:


I use the following which works fine, may be of help (plugging in your arguments)

var p = new Process
                            {
                                StartInfo =
                                    {
                                        UseShellExecute = false,
                                        FileName = "SCHTASKS.exe",
                                        RedirectStandardError = true,
                                        RedirectStandardOutput = true,
                                        CreateNoWindow = true,
                                        WindowStyle = ProcessWindowStyle.Hidden,
                                        Arguments = arguments
                                    }
                            };
            p.Start();


来源:https://stackoverflow.com/questions/7993392/c-sharp-start-a-scheduled-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!