检查计划任务存在和检查状态

xbo*_*nez 6 c#

我使用以下代码更改远程主机上的计划任务的"运行方式:"用户名和密码.

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "SCHTASKS.exe";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

//p.StartInfo.Arguments = String.Format("/Change /TN {0} /RU {1} /RP {2}",ScheduledTaskName,userName,password);
p.StartInfo.Arguments = String.Format(
    "/Change /S {0} /TN {1} /TR {2} /RU {3}\\{4} /RP {5}", 
    MachineName, ScheduledTaskName, taskPath, activeDirectoryDomainName, userName, password);

p.Start();
// Read the error stream first and then wait.
string error = p.StandardError.ReadToEnd();
p.WaitForExit();
Run Code Online (Sandbox Code Playgroud)

我有一些问题:

  1. 如何检查指定的服务是否存在,如果它不存在,我可以退出该程序.
  2. 如何查看计划任务是否正在运行或已禁用?
  3. 如果已禁用计划任务,是否仍可以更改凭据,或者它是否像Windows服务,如果禁用凭据,则无法更改凭据?

Gab*_*ams 7

看看我在上一个回答中给你的链接.SCHTASKS.exe的链接.

看看这个叫做的部分 Querying for Task Information.

这是我检查当前运行状态的代码.您可以使用输出来根据需要进行修改.

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "SCHTASKS.exe";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

p.StartInfo.Arguments = String.Format("/Query /S {0} /TN {1} /FO TABLE /NH", MachineName, ScheduledTaskName);

p.Start();
// Read the error stream
string error = p.StandardError.ReadToEnd();

//Read the output string
p.StandardOutput.ReadLine();
string tbl = p.StandardOutput.ReadToEnd();

//Then wait for it to finish
p.WaitForExit();

//Check for an error
if (!String.IsNullOrWhiteSpace(error))
{
    throw new Exception(error);
}

//Parse output
return tbl.Split(new String[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim().EndsWith("Running");
Run Code Online (Sandbox Code Playgroud)


Joe*_* DF 7

我知道这有点晚了,但我真的很想发布这个.(这是因为我喜欢简单的代码):D

用法示例:

MessageBox.Show("The scheduled task's existance is " + taskexistance("TASKNAMEHERE").ToString());
Run Code Online (Sandbox Code Playgroud)

功能:

private string taskexistance(string taskname)
{
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = "schtasks.exe"; // Specify exe name.
    start.UseShellExecute = false;
    start.CreateNoWindow = true;
    start.WindowStyle = ProcessWindowStyle.Hidden;
    start.Arguments = "/query /TN " + taskname;
    start.RedirectStandardOutput = true;
    // Start the process.
    using (Process process = Process.Start(start))
    {
        // Read in all the text from the process with the StreamReader.
        using (StreamReader reader = process.StandardOutput)
        {
            string stdout = reader.ReadToEnd();
            if (stdout.Contains(taskname)) {
                return "true.";
            }
            else
            {
                return "false.";
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)