summary refs log tree commit diff
path: root/LibSystemdCli/CommandExecutor.cs
blob: 096f1c1a9360fda69ae7839d6b7c1d54f77aa48c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System.Diagnostics;

namespace LibSystemdCli;

public class CommandExecutor
{
    public static async Task<string> ExecuteCommand(string command, string args)
    {
        Console.WriteLine($"[{DateTime.Now:O}] Executing command: {command} {args}");
        var process = new Process
        {
            StartInfo =
            {
                FileName = command,
                Arguments = args,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false
            }
        };
        process.Start();
        var output = await process.StandardOutput.ReadToEndAsync();
        var error = await process.StandardError.ReadToEndAsync();
        await process.WaitForExitAsync();
        if (process.ExitCode != 0)
        {
            throw new Exception($"Command {command} {args} failed with exit code {process.ExitCode} and error: {error}");
        }
        
        return output;
    }
    
    public static async IAsyncEnumerable<string> ExecuteCommandAsync(string command, string args)
    {
        Console.WriteLine($"[{DateTime.Now:O}] Executing command asynchronously: {command} {args}");
        var process = new Process
        {
            StartInfo =
            {
                FileName = command,
                Arguments = args,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false
            }
        };
        process.Start();
        while (!process.StandardOutput.EndOfStream)
        {
            var line = await process.StandardOutput.ReadLineAsync();
            yield return line;
        }
        await process.WaitForExitAsync();
        if (process.ExitCode != 0)
        {
            throw new Exception($"Command {command} {args} failed with exit code {process.ExitCode}");
        }
    }
}