-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessExecutionResult.cs
107 lines (92 loc) · 3.85 KB
/
ProcessExecutionResult.cs
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
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace PowershellScriptTimestamp
{
internal class ProcessExecutionResult
{
public string ExecutablePath { get; }
public string CommandLineArguments { get; }
public bool Successful { get; }
public int ExitCode { get; }
public string Stdout { get; }
public string Stderr { get; }
public ProcessExecutionResult(string path, string arguments)
{
ExecutablePath = path;
CommandLineArguments = arguments;
var outStringBuilder = new StringBuilder();
var errStringBuilder = new StringBuilder();
using (var process = new Process())
try
{
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Arguments = arguments;
process.StartInfo.FileName = path;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
using (AutoResetEvent stdoutConsumed = new AutoResetEvent(false))
using (AutoResetEvent stderrConsumed = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, evtArgs) =>
{
if (evtArgs.Data == null)
{
stdoutConsumed.Set();
}
else
{
outStringBuilder.AppendLine(evtArgs.Data);
}
};
process.ErrorDataReceived += (sender, evtArgs) =>
{
if (evtArgs.Data == null)
{
stderrConsumed.Set();
}
else
{
errStringBuilder.AppendLine(evtArgs.Data);
}
};
Console.WriteLine($"[INFO] About to run process {path} with arguments {arguments}.");
if (!process.Start())
{
Console.WriteLine($"[ERROR] Could not start process.");
return;
}
try
{
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
stdoutConsumed.WaitOne();
stderrConsumed.WaitOne();
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Could not wait for end of process. Dumping exception.");
Console.WriteLine(ex);
return;
}
}
ExitCode = process.ExitCode;
Successful = true;
return;
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] Could not run process. Dumping exception.");
Console.WriteLine(ex);
}
finally
{
Stdout = outStringBuilder.ToString();
Stderr = errStringBuilder.ToString();
}
}
}
}