PowerShell Welcome to this addition of the PowerShell ABC's where you'll find 26 posts detailing a component of the PowerShell scripting language, one letter at a time.  Today's letter is the letter "R" and for it I'll cover the runspace.

If you've downloaded PowerShell, you may think of PowerShell as a console application that is a replacement for the old CMD.EXE console.  That is true in that the process is called PowerShell.exe, but there is much more to it.  PowerShell is simply a console application that hosts the PowerShell runtime using a console window as a mechanism for allowing the user to interact with the runtime.

treadmill The core to PowerShell is the runtime, the execution engine that implements command processing. It includes the classes that provide the interface between the hosting application and PowerShell commands and providers. The PowerShell runtime is implemented as a runspace object for the current PowerShell session, which is the operational environment in which the shell and the commands execute.

A runspace provides a way for a hosting application to execute pipelines programmatically.  Runspaces construct a logical model of execution using pipelines that contains Cmdlets, native commands, and language elements. 

Runspaces are created using the RunspaceFactory class located in the System.Management.Automation.Runspaces namespace in the .NET framework.  The following example creates a Runspace based off the RunspaceConfiguration defined in the MyConsole.psc1 configuration file.

PSConsoleLoadException warnings;
RunspaceConfiguration config = RunspaceConfiguration.Create("MyConsole.psc1", out warnings);
if ( null == warnings )
Runspace myRs = RunspaceFactory.CreateRunspace(config);

PowerShell operates in a hosting application (the default that we've talked about is PowerShell.exe) that exposes a command line to the user, and uses a host interface to communicate with the commands invoked by the command line.  The hosting application can be any type of application including a console application, a windows application, or a web application.  The following diagram was taken from the How Windows PowerShell Works article on MSDN illustrates the components needed to make a hosting application for PowerShell.


Communications between the hosting application and the underlying pipeline can either be displayed directly by the hosting application or with the host directly through one of two optional host interfaces that can be specified when the runspace is configured.  For more information on creating a Hosting Application, see the article "How to Create a Windows PowerShell Hosting Application" on MSDN.

*Portions of this are taken from the PowerShell documentation on MSDN, thanks guys!