-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTypeDefinition.cs
More file actions
54 lines (45 loc) · 1.64 KB
/
TypeDefinition.cs
File metadata and controls
54 lines (45 loc) · 1.64 KB
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
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
//Add For PowerShell Invocation
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
[ComVisible(true)]
public class PowerShellHelper {
Runspace runspace;
public PowerShellHelper() {
runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
}
public PowerShellHelper(Runspace remoteRunspace) {
runspace = remoteRunspace;
}
void InvokePowerShell(string cmd, dynamic callbackFunc) {
using (PowerShell PowerShellInstance = PowerShell.Create()) {
PowerShellInstance.AddScript(cmd);
Collection<PSObject> results = PowerShellInstance.Invoke();
//Convert records to strings
StringBuilder stringBuilder = new StringBuilder();
if (PowerShellInstance.HadErrors) {
foreach(var errorRecord in PowerShellInstance.Streams.Error) {
stringBuilder.Append(errorRecord.ToString());
}
} else {
foreach(PSObject obj in results) {
stringBuilder.Append(obj);
}
}
callbackFunc(stringBuilder.ToString());
}
}
public void runPowerShell(string cmd, dynamic callbackFunc) {
new Task(() => { InvokePowerShell(cmd, callbackFunc); }).Start();
}
public void resetRunspace() {
runspace.Close();
runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
}
}