Несколько методов выполнения команды CMD на C# и получения вывода

Чтобы выполнить команду на C# и получить ее выходные данные, вы можете использовать несколько методов в зависимости от ваших конкретных требований. Вот несколько часто используемых подходов:

Метод 1: использование System.Diagnostics.Process

using System;
using System.Diagnostics;
class Program
{
    static void Main()
    {
        string command = "your_command_here";

        Process process = new Process();
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = "/c " + command;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;

        process.Start();

        string output = process.StandardOutput.ReadToEnd();

        process.WaitForExit();

        Console.WriteLine(output);
    }
}

Метод 2. Использование System.Management Automation

using System;
using System.Management.Automation;
class Program
{
    static void Main()
    {
        string command = "your_command_here";

        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            PowerShellInstance.AddScript(command);
            var result = PowerShellInstance.Invoke();

            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Метод 3: использование System.Diagnostics.ProcessStartInfo

using System;
using System.Diagnostics;
class Program
{
    static void Main()
    {
        string command = "your_command_here";

        ProcessStartInfo psi = new ProcessStartInfo("cmd.exe")
        {
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        Process process = Process.Start(psi);

        if (process != null)
        {
            process.StandardInput.WriteLine(command);
            process.StandardInput.Close();

            string output = process.StandardOutput.ReadToEnd();

            process.WaitForExit();

            Console.WriteLine(output);
        }
    }
}