ProcessRunner.ProcessHelper.ps1
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
[string]$ProcessHelperClassDefinition = @'
namespace ProcessRunner { using System; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Linq; using System.Text; /// <summary> /// Utility to orchestrate executing applications /// </summary> public static class ProcessHelper { /// <summary> /// Runs an application with arguments in three distinct modes. /// - Utility mode that runs the application synchronously, captures output/error streams and returns them as strings /// - Interactive mode for applications like cmd.exe, powershell/pwsh. Doesn't attempt to capture output/error streams. /// - Background mode running UI applications - returns without waiting for application termination. Doesn't attempt to capture output/error streams /// </summary> /// <param name="filePath"></param> /// <param name="arguments"></param> /// <param name="verb"></param> /// <param name="detachUiProcess"></param> /// <param name="interactive"></param> /// <returns></returns> public static ProcessResult Run(FileInfo filePath, List<string> arguments, string verb, bool detachUiProcess, bool interactive) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } if (!filePath.Exists) { throw new FileNotFoundException(string.Empty, filePath.FullName); } ProcessStartInfo psi = new ProcessStartInfo(filePath.FullName) { Arguments = string.Join(" ", arguments ?? Enumerable.Empty<string>()), UseShellExecute = false, Verb = verb, RedirectStandardOutput = !interactive, RedirectStandardError = !interactive, }; Process process = new Process() { StartInfo = psi }; StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); process.OutputDataReceived += delegate (object o, DataReceivedEventArgs e) { output.AppendLine(e.Data); }; process.Start(); if (!interactive) { process.BeginOutputReadLine(); } if (detachUiProcess) { do { process.WaitForExit(UiWaitTimeMilliSeconds); process.Refresh(); if (!process.HasExited && process.MainWindowHandle != IntPtr.Zero) { // break out of the wait-loop as soon as an HWND is detected break; } } while (!process.HasExited); } else { process.WaitForExit(); } if (!interactive) { process.CancelOutputRead(); } if (!interactive && process.HasExited && process.ExitCode != 0) { error.Append(process.StandardError.ReadToEnd()); } if (process.HasExited) { return new ProcessResult(filePath.FullName, arguments?.ToArray(), output.ToString(), error.ToString(), process.ExitCode); } else { return new RunningProcessResult(filePath.FullName, arguments?.ToArray(), process); } } /// <summary> /// Runs an application with arguments in 'Utility' mode /// - Utility mode runs the application synchronously, captures output/error streams and returns them as strings /// </summary> /// <param name="filePath"></param> /// <param name="arguments"></param> /// <param name="verb"></param> /// <returns></returns> public static ProcessResult Run(FileInfo filePath, List<string> arguments, string verb) { return ProcessHelper.Run(filePath, arguments, verb, detachUiProcess: false, interactive: false); } /// <summary> /// Runs an application with arguments in 'Utility' mode /// - Utility mode runs the application synchronously, captures output/error streams and returns them as strings /// </summary> /// <param name="filePath"></param> /// <param name="arguments"></param> /// <returns></returns> public static ProcessResult Run(FileInfo filePath, List<string> arguments) { return ProcessHelper.Run(filePath, arguments, null); } /// <summary> /// Represents the result of process execution /// </summary> public class ProcessResult { /// <summary> /// Path to the executable /// </summary> public readonly string FilePath; /// <summary> /// Arguments to the application /// </summary> public readonly string[] Arguments; /// <summary> /// Output of the application /// </summary> public readonly string Output; /// <summary> /// Error generated by the application in the error-stream /// </summary> public readonly string Error; /// <summary> /// Exit-code of the process /// </summary> public readonly int? ExitCode; /// <summary> /// Creates a <see cref="ProcessResult"/> object /// </summary> /// <param name="filePath"></param> /// <param name="arguments"></param> /// <param name="output"></param> /// <param name="error"></param> /// <param name="exitCode"></param> public ProcessResult(string filePath, string[] arguments, string output, string error, int exitCode) : this(filePath, arguments, output, error) { this.ExitCode = exitCode; } /// <summary> /// Creates a ProcessResult object /// </summary> /// <param name="filePath"></param> /// <param name="arguments"></param> /// <param name="output"></param> /// <param name="error"></param> protected ProcessResult(string filePath, string[] arguments, string output, string error) { this.FilePath = filePath; this.Arguments = arguments; this.Output = output; this.Error = error; this.ExitCode = null; } } /// <summary> /// Represents the result of executing a process in the background /// </summary> public class RunningProcessResult : ProcessResult { /// <summary> /// <see cref="Process"/> object representing a running process. /// </summary> public readonly Process Process; /// <summary> /// Creates a <see cref="RunningProcessResult"/> instances /// </summary> /// <param name="filePath"></param> /// <param name="arguments"></param> /// <param name="process"></param> public RunningProcessResult(string filePath, string[] arguments, Process process) : base(filePath, arguments, string.Empty, string.Empty) { this.Process = process; } } private const int UiWaitTimeMilliSeconds = 250; } } '@ Add-Type -TypeDefinition $ProcessHelperClassDefinition |