forked from canneverbe/Ketarin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PowerShellScript.cs
93 lines (77 loc) · 3.31 KB
/
PowerShellScript.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
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Text;
using Ketarin.Forms;
namespace Ketarin
{
internal class PowerShellScript
{
private readonly string scriptText;
public PowerShellScript(string scriptText)
{
this.scriptText = scriptText;
}
public string LastOutput { get; private set; } = string.Empty;
internal void Execute(ApplicationJob application, ApplicationJobError errorInfo = null)
{
using (PowerShell powerShell = PowerShell.Create())
{
powerShell.AddScript(this.scriptText);
// Make application object available to the script.
if (application != null)
{
powerShell.Runspace.SessionStateProxy.SetVariable("app", application);
}
if (errorInfo != null)
{
powerShell.Runspace.SessionStateProxy.SetVariable("apperror", errorInfo);
}
powerShell.Runspace.SessionStateProxy.SetVariable("globalvars", UrlVariable.GlobalVariables);
// Output all information we can get.
powerShell.Streams.Debug.DataAdded += this.DebugDataAdded;
powerShell.Streams.Warning.DataAdded += this.WarningDataAdded;
try
{
powerShell.Streams.Information.DataAdded += this.InfoDataAdded;
}
catch (MissingMethodException)
{
// Only supported in PS 5.0 and higher
}
Collection<PSObject> psOutput = powerShell.Invoke();
foreach (PSObject outputItem in psOutput)
{
// if null object was dumped to the pipeline during the script then a null
// object may be present here. check for null to prevent potential NRE.
if (outputItem != null)
{
this.LastOutput = outputItem.ToString();
LogDialog.Log("PowerShell: " + outputItem);
}
}
if (powerShell.HadErrors)
{
StringBuilder sb = new StringBuilder();
foreach (ErrorRecord error in powerShell.Streams.Error)
{
sb.AppendLine(error.Exception.Message);
}
throw new ApplicationException(sb.ToString());
}
}
}
private void InfoDataAdded(object sender, DataAddedEventArgs e)
{
LogDialog.Log("PowerShell (info): " + ((PSDataCollection<InformationRecord>) sender)[e.Index].MessageData);
}
private void WarningDataAdded(object sender, DataAddedEventArgs e)
{
LogDialog.Log("PowerShell (warning): " + ((PSDataCollection<WarningRecord>) sender)[e.Index].Message);
}
private void DebugDataAdded(object sender, DataAddedEventArgs e)
{
LogDialog.Log("PowerShell (debug): " + ((PSDataCollection<DebugRecord>) sender)[e.Index].Message);
}
}
}