-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExecutor.cs
More file actions
40 lines (33 loc) · 1.29 KB
/
Executor.cs
File metadata and controls
40 lines (33 loc) · 1.29 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
using System;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace BetterSharpPick.Scripting
{
public static class Executor
{
public static string Execute(string script)
{
if (script == null) throw new ArgumentNullException(nameof(script));
using (var runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (var ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddScript("$ErrorActionPreference = 'Continue';", useLocalScope: true);
ps.AddScript(script + " 6>&1", useLocalScope: true);
Collection<PSObject> results = ps.Invoke();
if (ps.Streams.Error != null && ps.Streams.Error.Count > 0)
{
var err = string.Join(Environment.NewLine, ps.Streams.Error.Select(e => e.ToString()));
throw new InvalidOperationException(err);
}
return string.Join(Environment.NewLine, results.Select(r => r?.ToString())).TrimEnd();
}
}
}
}
}