-
Notifications
You must be signed in to change notification settings - Fork 13
/
PowershellRunner.cs
270 lines (230 loc) · 8.78 KB
/
PowershellRunner.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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
using System.Text;
using System.Text.RegularExpressions;
using DynamicPowerShellApi.Exceptions;
using DynamicPowerShellApi.Model;
namespace DynamicPowerShellApi
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading.Tasks;
/// <summary>
/// The PowerShell runner.
/// </summary>
public class PowershellRunner : IRunner
{
/// <summary> The asynchronous execution method. </summary>
/// <remarks> Anthony, 5/27/2015. </remarks>
/// <exception cref="ArgumentException"> Thrown when one or more arguments have
/// unsupported or illegal values. </exception>
/// <exception cref="ArgumentNullException"> Thrown when one or more required arguments
/// are null. </exception>
/// <exception cref="PSSnapInException"> . </exception>
/// <exception cref="PowerShellExecutionException"> Thrown when a Power Shell Execution error
/// condition occurs. </exception>
/// <param name="filename"> The filename. </param>
/// <param name="snapin"> The snap in. </param>
/// <param name="module"> The module. </param>
/// <param name="parametersList"> The parameters List. </param>
/// <param name="asJob"> Run this command as a job. </param>
/// <returns> The <see cref="Task"/>. </returns>
public Task<PowershellReturn> ExecuteAsync(
string filename,
string snapin,
string module,
IList<KeyValuePair<string, string>> parametersList,
bool asJob)
{
if (string.IsNullOrWhiteSpace(filename))
throw new ArgumentException("Argument cannot be null, empty or composed of whitespaces only", "filename");
if (parametersList == null)
throw new ArgumentNullException("parametersList", "Argument cannot be null");
// Raise an event so we know what is going on
try
{
var sb = new StringBuilder();
foreach (KeyValuePair<string, string> kvp in parametersList)
{
if (sb.Length > 0)
sb.Append(";");
sb.Append(string.Format("{0}:{1}", kvp.Key, kvp.Value));
}
DynamicPowershellApiEvents
.Raise
.ExecutingPowerShellScript(filename, sb.ToString());
}
catch (Exception)
{
DynamicPowershellApiEvents
.Raise
.ExecutingPowerShellScript(filename, "Unknown");
}
try
{
string strBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string scriptContent = File.ReadAllText(Path.Combine(strBaseDirectory, Path.Combine("ScriptRepository", filename)));
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
if (!String.IsNullOrWhiteSpace(snapin))
{
PSSnapInException snapInException;
rsConfig.AddPSSnapIn(snapin, out snapInException);
if (snapInException != null)
{
DynamicPowershellApiEvents
.Raise
.SnapinException(snapInException.Message);
throw snapInException;
}
}
InitialSessionState initialSession = InitialSessionState.Create();
if (!String.IsNullOrWhiteSpace(module))
{
DynamicPowershellApiEvents
.Raise
.LoadingModule(module);
initialSession.ImportPSModule(new[] { module });
}
using (PowerShell powerShellInstance = PowerShell.Create(initialSession))
{
powerShellInstance.RunspacePool = RunspacePoolWrapper.Pool;
if (powerShellInstance.Runspace == null)
{
powerShellInstance.Runspace = RunspaceFactory.CreateRunspace(rsConfig);
powerShellInstance.Runspace.Open();
}
powerShellInstance.AddScript(scriptContent);
foreach (var item in parametersList)
powerShellInstance.AddParameter(item.Key, item.Value);
// invoke execution on the pipeline (collecting output)
Collection<PSObject> psOutput = powerShellInstance.Invoke();
string sMessage = psOutput == null
? String.Empty
: (
psOutput.LastOrDefault() != null
? Regex.Replace(psOutput.LastOrDefault().ToString(), @"[^\u0000-\u007F]", string.Empty)
: String.Empty);
DynamicPowershellApiEvents.Raise.PowerShellScriptFinalised("The powershell has completed - anlaysing results now");
// check the other output streams (for example, the error stream)
if (powerShellInstance.HadErrors && powerShellInstance.Streams.Error.Count > 0)
{
var runtimeErrors = new List<PowerShellException>();
// Create a string builder for the errors
StringBuilder sb = new StringBuilder();
// error records were written to the error stream.
// do something with the items found.
sb.Append("PowerShell script raised errors:" + Environment.NewLine);
sb.Append(String.Format("{0}", sMessage));
var errors = powerShellInstance.Streams.Error.ReadAll();
if (errors != null)
{
foreach (var error in errors)
{
if (error.ErrorDetails == null)
DynamicPowershellApiEvents.Raise.UnhandledException("error.ErrorDetails is null");
string errorDetails = error.ErrorDetails != null ? error.ErrorDetails.Message : String.Empty;
string scriptStack = error.ScriptStackTrace ?? String.Empty;
string commandPath = error.InvocationInfo.PSCommandPath ?? String.Empty;
if (error.ScriptStackTrace == null)
DynamicPowershellApiEvents.Raise.UnhandledException("error.ScriptStackTrace is null");
if (error.InvocationInfo == null)
DynamicPowershellApiEvents.Raise.UnhandledException("error.InvocationInfo is null");
else
{
if (error.InvocationInfo.PSCommandPath == null)
DynamicPowershellApiEvents.Raise.UnhandledException("error.InvocationInfo.PSCommandPath is null");
}
if (error.Exception == null)
DynamicPowershellApiEvents.Raise.UnhandledException("error.Exception is null");
DynamicPowershellApiEvents.Raise.PowerShellError(
errorDetails,
scriptStack,
commandPath,
error.InvocationInfo.ScriptLineNumber);
runtimeErrors.Add(new PowerShellException
{
StackTrace = scriptStack,
ErrorMessage = errorDetails,
LineNumber = error.InvocationInfo != null ? error.InvocationInfo.ScriptLineNumber : 0,
ScriptName = filename
});
if (error.Exception != null)
{
sb.Append(String.Format("PowerShell Exception {0} : {1}", error.Exception.Message, error.Exception.StackTrace));
}
sb.Append(String.Format("Error {0}", error.ScriptStackTrace));
}
}
else
{
sb.Append(sMessage);
}
DynamicPowershellApiEvents.Raise.PowerShellScriptFinalised(String.Format("An error was rasied {0}", sb));
throw new PowerShellExecutionException(sb.ToString())
{
Exceptions = runtimeErrors,
LogTime = DateTime.Now
};
}
var psGood = new PowershellReturn
{
PowerShellReturnedValidData = true,
ActualPowerShellData = sMessage
};
DynamicPowershellApiEvents.Raise.PowerShellScriptFinalised(String.Format("The powershell returned the following {0}", psGood.ActualPowerShellData));
return Task.FromResult(psGood);
}
}
catch (Exception runnerException)
{
if (runnerException.GetType() == typeof(PowerShellExecutionException))
throw;
DynamicPowershellApiEvents.Raise.UnhandledException(runnerException.Message, runnerException.StackTrace);
throw new PowerShellExecutionException(runnerException.Message)
{
Exceptions = new List<PowerShellException>
{
new PowerShellException
{
ErrorMessage = runnerException.Message,
LineNumber = 0,
ScriptName = "PowerShellRunner.cs",
StackTrace = runnerException.StackTrace
}
},
LogTime = DateTime.Now
};
}
}
/// <summary> Gets a job. </summary>
/// <remarks> Anthony, 5/29/2015. </remarks>
/// <param name="jobId"> Identifier for the job. </param>
/// <returns> The job. </returns>
public Task<PowershellReturn> GetJob(Guid jobId)
{
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
InitialSessionState initialSession = InitialSessionState.Create();
using (PowerShell powerShellInstance = PowerShell.Create(initialSession))
{
powerShellInstance.RunspacePool = RunspacePoolWrapper.Pool;
if (powerShellInstance.Runspace == null)
{
powerShellInstance.Runspace = RunspaceFactory.CreateRunspace(rsConfig);
powerShellInstance.Runspace.Open();
}
ICollection<PSJobProxy> jobProxyCollection = PSJobProxy.Create(powerShellInstance.Runspace);
var proxy = jobProxyCollection.First();
return Task.FromResult(
new PowershellReturn
{
PowerShellReturnedValidData = true,
ActualPowerShellData = proxy.Output.LastOrDefault().ToString()
}
);
}
}
}
}