Calling Powershell functions from C#

Sean picture Sean · Nov 14, 2010 · Viewed 15.9k times · Source

I have a PS1 file with multiple Powershell functions in it. I need to create a static DLL that reads all the functions and their definitions in memory. It then invokes one of these functions when a user calls the DLL and passes in the function name as well as the parameters for the function.

My question is, is it possible to do this. ie call a function that has been read and stored in memory?

Thanks

Answer

Amr Reda picture Amr Reda · Apr 22, 2014

Here's the equivalent C# code for the code mentioned above

string script = "function Test-Me($param1, $param2) { \"Hello from Test-Me with $param1, $param2\" }";

using (var powershell = PowerShell.Create())
{
    powershell.AddScript(script, false);

    powershell.Invoke();

    powershell.Commands.Clear();

    powershell.AddCommand("Test-Me").AddParameter("param1", 42).AddParameter("param2", "foo");

    var results = powershell.Invoke();
}