-
Notifications
You must be signed in to change notification settings - Fork 164
/
powashell.csproj
78 lines (66 loc) · 3.18 KB
/
powashell.csproj
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
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This inline task executes c# code. -->
<!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe powaShell.csproj -->
<Target Name="Hello">
<ClassExample />
</Target>
<UsingTask
TaskName="ClassExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
<Task>
<Reference Include="C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll" />
<!-- Your PowerShell Path May vary -->
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
public class ClassExample : Task, ITask
{
public override bool Execute()
{
Console.WriteLine("Hello From a Class.");
Console.WriteLine(powaShell.RunPSCommand());
return true;
}
}
//Based on Jared Atkinson's And Justin Warner's Work
public class powaShell
{
public static string RunPSCommand()
{
//Init stuff
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.LanguageMode = PSLanguageMode.FullLanguage;
Runspace runspace = RunspaceFactory.CreateRunspace(iss);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
//Interrogate LockDownPolicy
Console.WriteLine(System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy());
//Add commands
pipeline.Commands.AddScript("[Math]::Sqrt(9)");
//Prep PS for string output and invoke
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
//Convert records to strings
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.Append(obj);
}
return stringBuilder.ToString().Trim();
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>