Skip to content

Instantly share code, notes, and snippets.

@farzinenddo
Created March 23, 2020 18:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farzinenddo/bb1f1ecb56aa9326abc7b47fc99e588e to your computer and use it in GitHub Desktop.
Save farzinenddo/bb1f1ecb56aa9326abc7b47fc99e588e to your computer and use it in GitHub Desktop.
Running Powershell with CLR in native runtime.
#include <metahost.h>
#pragma comment(lib, "mscoree.lib")
int main(int argc, wchar_t* argv[])
{
HRESULT hr;
ICLRMetaHost *pMetaHost = NULL;
ICLRRuntimeInfo *pRuntimeInfo = NULL;
ICLRRuntimeHost *pClrRuntimeHost = NULL;
// build runtime
hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));
hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost,IID_PPV_ARGS(&pClrRuntimeHost));
// start runtime
hr = pClrRuntimeHost->Start();
// execute managed assembly
DWORD pReturnValue;
hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(
L"Powerless\\bin\\Release\\Powerless.dll",
L"Powerless.Program",
L"run",
L"start-process calc;",
&pReturnValue);
// free resources
pMetaHost->Release();
pRuntimeInfo->Release();
pClrRuntimeHost->Release();
return 0;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Threading;
namespace Powerless
{
public class Program
{
static int run(String pwzArgument)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(pwzArgument);
IAsyncResult result = PowerShellInstance.BeginInvoke();
while (result.IsCompleted == false)
{
Console.WriteLine("Waiting for pipeline to finish...");
Thread.Sleep(1000);
}
Console.WriteLine("Finished!");
Console.ReadKey();
}
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment