RunspaceFactory.CreateRunspace Method ()

 

Updated: April 27, 2016

Applies To: Windows PowerShell

Creates a single runspace that uses the default host and runspace configuration.

Namespace:   System.Management.Automation.Runspaces
Assembly:  System.Management.Automation (in System.Management.Automation.dll)

public static Runspace CreateRunspace()

Return Value

Type: System.Management.Automation.Runspaces.Runspace

Returns a Runspace object that represents the runspace. When this runspace is opened, the default host and runspace configuration that are defined by Windows PowerShell will be used.

A runspace is the operating environment used when invoking the commands of a pipeline. After the runspace is created, it must be opened by using one of the following methods before it can be used:

  • To open the runspace synchronously, call the Open method.

  • To open the runspace asynchronously, call the OpenAsync method.

When using the default host, there is no way to interact or communicate directly with the user through prompting.

This example creates a runspace, opens it synchronously, and then uses the runspace when the pipeline is invoked.

using System;
using System.Management.Automation;           // Windows PowerShell namespace.
using System.Management.Automation.Runspaces; // Windows PowerShell namespace.

namespace HostPS4
{
  class HostPS4
  {
    static void Main(string[] args)
    {

    // Call the CreateRunspace() method to create the 
    // runspace. This call does not specify any 
    // configuration information such as a custom host 
    // or intial session state informtion.
    Runspace rs = RunspaceFactory.CreateRunspace();
    rs.Open();


      // Call the Create() method to create the PowerShell 
      // object, and then specify the runspace and 
      // create the pipeline.
      PowerShell ps = PowerShell.Create();
      ps.Runspace = rs;
      ps.AddCommand("Get-Process").AddArgument("wmi*");

      Console.WriteLine("Process               Id");
      Console.WriteLine("------------------------");


      // Using the PowerShell object, invoke the pipeline 
      // synchronously.
      foreach (PSObject result in ps.Invoke())
      {
        Console.WriteLine("{0,-20}{1}",
                result.Members["ProcessName"].Value,
                result.Members["Id"].Value);
      } // End foreach.
    } // End Main.
  } // End HostPS4.
}

Return to top

Community Additions

ADD
Show: