Example #1
0
        /// <summary>
        /// Processes the command output to check if the stream was redirected to the stream to the
        /// standard error output device, and if so, throws it as an exception.
        /// </summary>
        /// <param name="cmdOutput">Output from an executed command.</param>
        /// <returns>Text from the standard output device.</returns>
        /// <exception cref="StandardErrorException">Text from the standard error output device.</exception>
        private static string ProcessOutput(CommandOutput cmdOutput)
        {
            if (cmdOutput.ExitCode > 0)
            {
                throw new StandardErrorException(cmdOutput.StdErr);
            }

            return(cmdOutput.StdOut);
        }
Example #2
0
        /// <summary>
        /// Runs a shell command on a host system.
        /// </summary>
        /// <param name="command">Command to run.</param>
        /// <returns>Output from the executed command.</returns>
        public CommandOutput Run(string command)
        {
            var cmdOutput = new CommandOutput()
            {
                ExitCode = 1
            };
            var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            var startInfo = new ProcessStartInfo()
            {
                FileName  = isWindows ? "cmd.exe" : "/bin/bash",
                Arguments = isWindows ? $"/c \"{command}\"" : $"-c \"{command}\"",
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                StandardOutputEncoding = Encoding.UTF8,
                UseShellExecute        = false,
                CreateNoWindow         = true
            };

            try
            {
                using (var process = Process.Start(startInfo))
                {
                    if (process == null)
                    {
                        throw new InvalidOperationException("Failed to execute command.");
                    }
                    cmdOutput.StdOut = process.StandardOutput.ReadToEnd().Trim();
                    cmdOutput.StdErr = process.StandardError.ReadToEnd().Trim();
                    process.WaitForExit();
                    cmdOutput.ExitCode = process.ExitCode;
                }
            }
            catch (Exception ex)
            {
                cmdOutput.StdErr = ex.Message;
            }

            return(cmdOutput);
        }