выполнить несколько команд cmd в одной строке - PullRequest
0 голосов
/ 11 октября 2019

У меня есть несколько команд, и я хотел выполнить их в одной строке, используя 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;
}
...