首页 > 解决方案 > 在一行中执行多个 cmd 命令

问题描述

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

for /f ... do xxxx...

然后在完成上面的命令后执行另一个多个命令。

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

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

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

标签: c#windowswinformscmdcommand-line

解决方案


推荐阅读