从c#调用powershell函数的问题

use*_*240 5 c# powershell

我正在尝试调用powershell文件中的函数,如下所示:

    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());
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

powershell函数在CallPS.ps1中:

Function BatAvg
{
    param ($Name, $Runs, $Outs)
    $Avg = [int]($Runs / $Outs*100)/100 
    Write-Output "$Name's Average = $Avg, $Runs, $Outs "
}
Run Code Online (Sandbox Code Playgroud)

我收到以下异常:

术语"BatAvg"不被识别为cmdlet,函数,脚本文件或可操作程序的名称.

我承认,我做错了什么,我对PowerShell知之甚少.

man*_*lds 7

这似乎对我有用:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)