Start a scheduled task in C#
Asked Answered
L

3

15

I'm trying to write a simple form in C# that will run a scheduled task one some computers.

What 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?

Legislature answered 3/11, 2011 at 10:32 Comment(2)
"For some reason" - what reason? It could be anything. Do you have any error messages? When you run this code in the debugger does Process.Start return a value - i.e. the Process?Concessive
Have you confirmed the string to start ends up identical to what you test in the command prompt?Starla
C
10

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

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

Contuse answered 3/11, 2011 at 10:45 Comment(0)
L
10

using Microsoft.Win32.TaskScheduler;

using (TaskService tasksrvc = new TaskService(@"\\" + servername, username, domain, password, true))
{       
    Task task = tasksrvc.FindTask(taskSchedulerName);
    task.Run();
}   
Lovash answered 23/3, 2017 at 5:10 Comment(0)
B
2

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();
Basin answered 3/11, 2011 at 10:45 Comment(3)
When I try to run a scheduled task, I'm getting "permission denied" on Win10 machine... Any idea why?Martyrology
@Martyrology I'm assuming you're running within Visual Studio or Rider. You will need elevated rights to do so. That is close the IDE and then run as administrator and you will have the rights to create the taskBasin
I got the issue, sorry for nagging. ;) I'm running Process.Start from a ASPX Page, while IIS-Runtime is not allowed to start processes on the local machine for security reasons. Workaround is to use a custom Windows Service to accomplish this. (Just to round up the info for following readers)Martyrology

© 2022 - 2024 — McMap. All rights reserved.