多次打开运行空间

时间:2015-04-25 10:33:48

标签: c# .net powershell c#-4.0 dotnet-httpclient

我想从C#在远程计算机上执行powershell命令。我使用

实现了同样的目标
    public Collection<PSObject> RunScript(String Command)
    {
        Collection<PSObject> results = null;
        using (var powershell = PowerShell.Create())
        {
         Runspace runspace = RunspaceFactory.CreateRunspace(connection);
         runspace.Open();
         powershell.Runspace = runspace();
          powershell.AddScript(Command);
          results = powershell.Invoke();
          runspace.Close();
      }
            return results;
        }
    }

我能够第一次执行此操作。但是当我第二次尝试执行这个函数时,它给了我错误,运行空间被关闭。实际上我最后关闭了它,但为什么在调用函数时它不会重新打开。

1 个答案:

答案 0 :(得分:1)

你关闭了它,但你没有丢弃它:

using (var powershell = PowerShell.Create())
using (Runspace runspace = RunspaceFactory.CreateRunspace(connection))
{
    runspace.Open();
    powershell.Runspace = runspace();
    powershell.AddScript(Command);
    results = powershell.Invoke();
    runspace.Close();
}
相关问题