我需要获取在某个主机上运行的所有计划任务列表到C#中的列表或数组中.
查询
schtasks /query /S CHESTNUT105B /FO List
Run Code Online (Sandbox Code Playgroud)
返回如下列表:
HostName: CHESTNUT105B
TaskName: Calculator
Next Run Time: 12:00:00, 10/28/2010
Status: Running
HostName: CHESTNUT105B
TaskName: GoogleUpdateTaskMachineCore
Next Run Time: At logon time
Status:
HostName: CHESTNUT105B
TaskName: GoogleUpdateTaskMachineCore
Next Run Time: 13:02:00, 10/28/2010
Run Code Online (Sandbox Code Playgroud)
我有以下代码来执行我上面指定的命令:
static void Main(string[] args)
{
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;
string MachineName = "CHESTNUT105b";
string ScheduledTaskName = "Calculator";
string activeDirectoryDomainName = "xxx";
string userName = "xxx";
string password = "xxxxx";
p.StartInfo.Arguments = String.Format("/Query /S {0} /FO LIST", MachineName);
p.Start();
}
Run Code Online (Sandbox Code Playgroud)
如何在C#中读取生成列表的列表?
像这样的东西应该有效(未经测试)。这会将输出的每一行包含在列表的一个元素中。
class GetSchTasks {
List<string> output = new List<string>();
public void Run()
{
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;
string MachineName = "CHESTNUT105b";
string ScheduledTaskName = "Calculator";
string activeDirectoryDomainName = "xxx";
string userName = "xxx";
string password = "xxxxx";
p.StartInfo.Arguments = String.Format("/Query /S {0} /FO LIST", MachineName);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.WaitForExit();
p.Close();
p.Dispose();
}
void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
//Handle errors here
}
void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
output.Add(e.Data);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以稍后解释该列表以构建一组合适的对象来表示每个计划任务,也可以不表示,具体取决于实际用例。ScheduledTask您还可以在处理程序本身中构建 s 对象列表p_OutputDataReceived,只需将每一行与预期的开头进行比较,例如,if (e.Data.StartsWith("HostName:") ) { //parse the line and grab the host name }
| 归档时间: |
|
| 查看次数: |
3986 次 |
| 最近记录: |