using System.Diagnostics; namespace LibSystemdCli; public class CommandExecutor { public static async Task 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 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}"); } } }