2010-10-27 7 views
5

Estoy usando el siguiente código para cambiar el nombre de usuario y la contraseña 'Ejecutar como:' para una tarea programada en un host remoto.Verifique la existencia de tareas programadas y compruebe el estado

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(); 

Tengo un par de preguntas:

  1. ¿Cómo puedo comprobar si el servicio especificado existe en absoluto, de modo que si no existe, sólo puede salir del programa.
  2. ¿Cómo puedo verificar si la tarea programada se está ejecutando o está deshabilitada?
  3. Si la tarea programada está deshabilitada, ¿aún puedo cambiar las credenciales, o es como un servicio de Windows donde las credenciales no se pueden cambiar si está deshabilitado?

Respuesta

6

Mira el enlace que te di en my last answer. El enlace para SCHTASKS.exe.

vistazo a la sección llamada Querying for Task Information.

Aquí está mi código para comprobar el estado de funcionamiento actual. Puede jugar con la salida para modificar esto según sus necesidades.

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"); 
+0

La declaración de devolución muestra este error: Excepción no controlada: System.IndexOutOfRangeException: Index estaba fuera del boun ds de la matriz. – xbonez

+0

Cuando lo ejecuto, hay 2 líneas devueltas. La primera línea se ve así: 'Carpeta: \ '¿Tal vez la tuya es diferente? –

+0

cuando ejecuta el código anterior? No puedo ejecutarlo debido al error – xbonez

5

Sé que es un poco tarde pero, realmente quería publicar esto. (Es porque me gusta simple código): D

Ejemplo de uso:

MessageBox.Show("The scheduled task's existance is " + taskexistance("TASKNAMEHERE").ToString()); 

Función:

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."; 
      } 
     } 
    } 
} 
+1

Use 'Arguments ="/query/TN \ "" + taskname + "\" ";' en caso de que "taskname" contenga espacio. – Manish

+0

@manish ahh sí, buen punto –

-1

Sólo tiene que llamar schtask/consulta. La opción/TN no funcionó solo devolvió un ERROR. Pero si solo usa el/Query, puede buscar el resultado de la tarea.

Cuestiones relacionadas