先从参数和收集输出命令行(Start command line with parameters an

2019-10-31 03:34发布

ProcessStartInfo startInfo = new ProcessStartInfo();
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "tsvc -a -st rifs -h "+textBox1+" -sn "+textBox2+" -status";

Process process = new Process();
process.StartInfo = startInfo;
process.Start();

richTextBox1.Text = process.StandardOutput.ReadToEnd();
  1. 我需要运行在命令cmd ,将采取将被插入到textBox1的1和TextBox,然后将输出发送到richTextBox1 2个参数。

  2. 当运行这种方式获取:

    类型的第一次机会异常“System.InvalidOperationException”发生在System.dll中
    其他信息:StandardOut尚未被重定向或进程尚未开始

  3. 我试图排除输出线,当我做到这一点不运行CMD,但不输入任何命令(它只是打开一个CMD窗口和什么都不做)。

Answer 1:

Process.Start()异步启动一个新的进程。 当你到了process.StandardOutput.ReadToEnd()的过程还没有结束,因此例外。 您应该使用事件触发挂钩到OutputDataRecieved事件。 你想要做这样的事情:

        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.UseShellExecute = false;
        startInfo.CreateNoWindow = true;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/c tsvc -a -st rifs -h " + textBox1 + " -sn " + textBox2 + " -status";

        process.StartInfo = startInfo;
        process.OutputDataReceived += ProcessOnOutputDataReceived;
        process.ErrorDataReceived += ProcessOnOutputDataReceived;
        process.Start();

然后添加一个事件处理收到像这样的输出数据:

    private void ProcessOnOutputDataReceived(object sender, DataReceivedEventArgs dataReceivedEventArgs)
    {
        richTextBox1.Text += dataReceivedEventArgs.Data;
    }

此外,我不能肯定,但我认为你需要调用您的文本框的文字:

startInfo.Arguments = "/c tsvc -a -st rifs -h " + textBox1.Text + " -sn " + textBox2.Text + " -status";


Answer 2:

设法做到这一点与结束。

        richTextBox1.Text = "";
        int counter = 0 ,totalMemory=0;
        string line;
        string command = " /c ro -a -h " + textBox1.Text + " -sn HC* $$info Server Total = $servermemory Service Memory = $servicememory > c:\\noc\\ntb\\logs\\output.txt";
        ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command);
        Process proc = new Process();
        procStartInfo.CreateNoWindow = true;
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.RedirectStandardError = true;
        procStartInfo.UseShellExecute = false;
        proc.StartInfo = procStartInfo;
        proc.Start();
        proc.WaitForExit();


文章来源: Start command line with parameters and collection output