Q:

Opening runspaces multiple times

I want to execute a powershell command on a remote computer from C#. I have achieved the same using
    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;
        }
    }

I am able to execute this for first time. but when i try to executr this function for second time it gives me error, runspace is closed.actually i did close it at last but why doesnt it reopen when function is called.

A:

You closed it but you didn't dispose of it:
using (var powershell = PowerShell.Create())
using (Runspace runspace = RunspaceFactory.CreateRunspace(connection))
{
    runspace.Open();
    powershell.Runspace = runspace();
    powershell.AddScript(Command);
    results = powershell.Invoke();
    runspace.Close();
}

