How to read standard output from the command line through Process.Start () as a list or array

I need to get a list of all scheduled tasks running on a specific host into a list or array in C #.

Inquiry

schtasks /query /S CHESTNUT105B /FO List

returns a list like this:

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

I have the following code to execute the above command:

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

How can I read the list generated by the list in C #?

+5
source share
2 answers

Something like this should work (unverified). This will have every line of output in the list item.

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

}

, , , , . ScheduledTask p_OutputDataReceived, , , if (e.Data.StartsWith("HostName:") ) { //parse the line and grab the host name }

+3

question - "# "

StreamReader, , , , .

, , : str.split("\n\n") - , , .

+1

All Articles