[ACCEPTED]-Calling Powershell functions from C#-cmdlets

Accepted answer
Score: 19

Here's the equivalent C# code for the code 1 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();
}
Score: 5

It is possible and in more than one ways. Here 6 is probably the simplest one.

Given our functions 5 are in the MyFunctions.ps1 script (just one for this demo):

# MyFunctions.ps1 contains one or more functions

function Test-Me($param1, $param2)
{
    "Hello from Test-Me with $param1, $param2"
}

Then 4 use the code below. It is in PowerShell 3 but it is literally translatable to C# (you 2 should do that):

# create the engine
$ps = [System.Management.Automation.PowerShell]::Create()

# "dot-source my functions"
$null = $ps.AddScript(". .\MyFunctions.ps1", $false)
$ps.Invoke()

# clear the commands
$ps.Commands.Clear()

# call one of that functions
$null = $ps.AddCommand('Test-Me').AddParameter('param1', 42).AddParameter('param2', 'foo')
$results = $ps.Invoke()

# just in case, check for errors
$ps.Streams.Error

# process $results (just output in this demo)
$results

Output:

Hello from Test-Me with 42, foo

For more details 1 of the PowerShell class see:

http://msdn.microsoft.com/en-us/library/system.management.automation.powershell

More Related questions