【问题标题】:Problem with calling a powershell function from c#从 c# 调用 powershell 函数的问题
【发布时间】:2011-09-03 17:41:05
【问题描述】:

我正在尝试调用 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 知之甚少。

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    这似乎对我有用:

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

    【讨论】:

      【解决方案2】:

      看来Runspace 需要连接到Powershell 才能实现这一点 - 请参阅MSDN 的示例代码。

      【讨论】:

      • 不,仍然得到相同的异常:runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = 运行空间; ps.AddScript(脚本);命令 c = new Command("BatAvg",false); ps.AddCommand("BatAvg",false); ps.AddParameter("姓名", "约翰"); ps.AddParameter("运行", "6996"); ps.AddParameter("Outs", "70"); foreach (PSObject obj in ps.Invoke()) { // 做一些事情Console.WriteLine(obj.ToString()); }
      【解决方案3】:

      解决方案可以进一步简化,因为在这种情况下不需要非默认运行空间。

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

      另一个陷阱是使用AddScript(script, true) 来使用本地范围。将遇到相同的异常(即“术语 'BatAvg' 未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。”)。

      【讨论】:

        猜你喜欢
        • 2011-05-09
        • 1970-01-01
        • 2021-08-31
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        • 2020-05-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多