[英]How to read standard output from a command run via Process.Start() as a list or array
我需要獲取在某個主機上運行的所有計划任務列表到C#中的列表或數組中。
查詢
schtasks /query /S CHESTNUT105B /FO List
返回如下列表:
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
我有以下代碼來執行我上面指定的命令:
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();
}
如何在C#中讀取生成列表的列表?
這樣的事情應該有效(未經測試)。 這將在List的元素中具有每行輸出。
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);
}
}
現在,您可以在之后解釋該列表,以構建一組適當的對象來表示每個計划任務,具體取決於實際用例。 您還可以在p_OutputDataReceived
處理程序本身中構建一個ScheduledTask
對象列表,只需將每一行與預期的開頭進行比較,例如if (e.Data.StartsWith("HostName:") ) { //parse the line and grab the host name }
這個問題的一部分可以通過前一個問題回答 - “C#如何讀取帶參數的控制台輸出”
按照該問題中的建議將控制台輸出檢索到StreamReader后,您只需將控制台輸出解析為單個計划任務,然后解析為存儲您感興趣的每個數據的對象。
要分解單個任務,看起來你可以使用: str.split("\\n\\n")
- 這將為每個任務提供一個單獨的字符串,因此循環遍歷此數組,並創建一個讀取string並通過解析數據來填充其值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.