在一行中执行多个cmd命令

时间:2019-10-11 07:03:37

标签: c# windows winforms cmd command-line

我有多个命令,我想使用Process在一行中执行它们。第一个命令使用的是For loop

for /f ... do xxxx...

然后在完成上述命令后,再执行另一条命令。

& [command] & [command] & [command] & [command]

我了解使用&&&运算符,因此我尝试了以下命令,但没有结果。

for /f ... do xxxx... & [command] & [command] & [command] & [command]

总而言之,问题是在完成for loop之后发生的,第二条命令没有执行,由于&运算符,第二条命令应该有错误地执行。

我当前的解决方案是使用单独的处理方法,并在完成for loop命令后调用。

private string void cmd_command(){
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/K";
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WorkingDirectory = workingDirectory;
    process.StartInfo.UseShellExecute = false;
    process.Start();

    process.StandardInput.WriteLine(@"for /f ... do xxxx..."); 
    process.StandardInput.Flush();
    process.StandardInput.Close();
    process.WaitForExit();

    string response = process.StandardOutput.ReadToEnd();
    Console.WriteLine(response);

    if(response.ToUpperInvariant().Contains(expectedOutput)){
        //call second multiple command
        return next_cmd_command();
    }

    return null;
}

private string next_cmd_command(){
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/K";
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WorkingDirectory = workingDirectory;
    process.StartInfo.UseShellExecute = false;
    process.Start();

    process.StandardInput.WriteLine(@"[command] & [command] & [command] & [command]"); 
    process.StandardInput.Flush();
    process.StandardInput.Close();
    process.WaitForExit();

    string response = process.StandardOutput.ReadToEnd();
    Console.WriteLine(response);
    return response;
}

0 个答案:

没有答案