c# - 从 c# 调用 powershell 函数的问题

标签 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());
            }
        }
    }

powershell 函数在 CallPS.ps1 中:

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

我收到以下异常:

术语“BatAvg”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。

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

最佳答案

这似乎对我有用:

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);
    }
}

关于c# - 从 c# 调用 powershell 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294765/

相关文章:

powershell - Pester 没有捕捉到抛出的错误

c# - 将特殊字符转换为普通字符

c# - 寻找最合适的图像标准【图像识别】

c# - 在 ASP.Net Core 1.0 中注册通用 EntityFrameworkCore DbContext

powershell - 使用 set-acl 和 powershell 设置继承和传播标志

c# - 在 PowerShell cmdlet 中导航父子关系

c# - .NET 字符串和引用类型参数

c# - 如何在 C# 中将文件存储在共享网络驱动器上

电源外壳 : how to format get-date to string and remove 0's?

ios - Powershell New-SelfSignedCertificate CA 不适用于 iOS 14.2