Last active
May 12, 2021 08:13
-
-
Save NickTyrer/d00d40b30c946a97c22b11c9d2d17972 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Runtime.InteropServices; | |
| using RGiesecke.DllExport; | |
| using System.Management.Automation; | |
| using System.Collections.ObjectModel; | |
| using System.Text; | |
| namespace Export | |
| { | |
| class Test | |
| { | |
| //based on Casey Smith's work | |
| // | |
| // | |
| //rundll32 entry point | |
| [DllExport("GetCLRRuntimeHost", CallingConvention = CallingConvention.StdCall)] | |
| public static bool GetCLRRuntimeHost() | |
| { | |
| while (true) | |
| { | |
| Console.Write("PS >"); | |
| string x = Console.ReadLine(); | |
| try | |
| { | |
| Console.WriteLine(RunPSCommand(x)); | |
| } | |
| catch (Exception e) | |
| { | |
| Console.WriteLine(e.Message); | |
| } | |
| } | |
| return true; | |
| } | |
| //Based on Jared Atkinson's And Justin Warner's Work | |
| public static string RunPSCommand(string cmd) | |
| { | |
| //Init stuff | |
| System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); | |
| runspace.Open(); | |
| RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); | |
| System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline(); | |
| //Add commands | |
| pipeline.Commands.AddScript(cmd); | |
| //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(); | |
| } | |
| public static void RunPSFile(string script) | |
| { | |
| PowerShell ps = PowerShell.Create(); | |
| ps.AddScript(script).Invoke(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment