Problem calling powershell function from C #

I am trying to call a function in a powershell file as follows:

    string script = System.IO.File.ReadAllText(@"C:\Users\Bob\Desktop\CallPS.ps1");

    using (Runspace runspace = RunspaceFactory.CreateRunspace())
    {
        runspace.Open();
        using (Pipeline pipeline = runspace.CreatePipeline(script))
        {
            Command c = new Command("BatAvg",false); 
            c.Parameters.Add("Name", "John"); 
            c.Parameters.Add("Runs", "6996"); 
            c.Parameters.Add("Outs", "70"); 
            pipeline.Commands.Add(c); 

            Collection<PSObject> results = pipeline.Invoke();
            foreach (PSObject obj in results)
            {
                // do somethingConsole.WriteLine(obj.ToString());
            }
        }
    }

The powershell function is in CallPS.ps1:

Function BatAvg
{
    param ($Name, $Runs, $Outs)
    $Avg = [int]($Runs / $Outs*100)/100 
    Write-Output "$Name Average = $Avg, $Runs, $Outs "
}

I get the following exception:

The term BatAvg is not recognized as the name of a cmdlet, function, script file, or executable program.

What am I doing wrong, I admit, I know very little about PowerShell.

+5
source share
3 answers

This seems to work for me:

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
    runspace.Open();
    PowerShell ps = PowerShell.Create();
    ps.Runspace = runspace;
    ps.AddScript(script);
    ps.Invoke();
    ps.AddCommand("BatAvg").AddParameters(new Dictionary<string, string>
    {
        {"Name" , "John"},
        {"Runs", "6996"},
        {"Outs","70"}
    });

    foreach (PSObject result in ps.Invoke())
    {
        Console.WriteLine(result);
    }
}
+7
source

It seems Runspaceyou need to connect to Powershellto make this work - see the example code on MSDN .

+1
source

, Runspace .

var ps = PowerShell.Create();
ps.AddScript(script);
ps.Invoke();
ps.AddCommand("BatAvg").AddParameters(new Dictionary<string, string>
{
     {"Name" , "John"}, {"Runs", "6996"}, {"Outs","70"}
});
foreach (var result in ps.Invoke())
{
     Console.WriteLine(result);
}

Another mistake is to use AddScript(script, true)to use the local area. The same exception will be encountered (that is, the term "BatAvg" is not recognized as the name of the cmdlet, function, script file or operational program. ").

+1
source

All Articles