【问题标题】:Powershell script getting called twice from C#.net code从 C#.net 代码调用 Powershell 脚本两次
【发布时间】:2014-05-02 06:34:26
【问题描述】:

我有以下代码,我从我的 C#.net 服务调用这导致两次调用 powershell 脚本。

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
      runspace.Open();

      runspace.SessionStateProxy.SetVariable("scriptpath", scriptPath);
      runspace.SessionStateProxy.SetVariable("DBRecordKey", reportId.Key);
      runspace.SessionStateProxy.SetVariable("SymbolPath", symbolPath);
      Logger.Log("DBRecordKey = " + reportId.Key, writer);
      using (Pipeline pipeline = runspace.CreatePipeline(scriptText))
      {
             //Here's how you add a new script with arguments
             pipeline.Commands.AddScript(scriptText);

             // Execute PowerShell script
             Collection<PSObject> results = pipeline.Invoke();

             StringBuilder outputString = new StringBuilder();
             foreach (PSObject obj in results)
             {
                     outputString.AppendLine(obj.ToString());
             }
             Logger.Log("outputString 2 - " + outputString, writer);
             pipeline.Stop();
             runspace.Close();
      }
}

我的代码有什么问题吗?

【问题讨论】:

    标签: c# windows powershell service runspace


    【解决方案1】:

    您在CreatePipeline(scriptText)AddScript(scriptText) 中都指定了脚本。 我不是 Powershell 用户,但我建议或者你想要

    using (Pipeline pipeline = runspace.CreatePipeline())
    {
        pipeline.Commands.AddScript(scriptText);
        ...
    }
    

    ...您想完全删除AddScript 调用。如果有特定原因需要AddScript,那么在没有scriptText 的情况下创建管道似乎是合乎逻辑的方法。

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      相关资源
      最近更新 更多