Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Runtime.InteropServices;
using RGiesecke.DllExport;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Text;
// compile using unmanaged exports and referencing system.management.automation
// rasautou -d powershell.dll -p powershell -a a -e e
namespace Export
{
class Test
{
[DllExport("powershell", CallingConvention = CallingConvention.StdCall)]
public static bool powershell()
{
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