concept runspace in category powershell

This is an excerpt from Manning's book Windows PowerShell in Action, Third Edition.
In this section, we’ll look at how runspaces, which are PowerShell engine instances, interact with the PowerShell API. A runspace is a container that holds everything needed to execute PowerShell code. This container holds all variables, drives, commands, and the like that are used during the execution of a [PowerShell] object invocation. A runspace is always required when you want to execute PowerShell code, regardless of the mechanism used to execute that code, either API or script. A script user, however, typically isn’t aware that there is a runspace because it was created by the host (for example, the PowerShell console host or the PowerShell ISE) application at startup. And so far, we as API users, haven’t dealt with runspaces directly because the way we’ve been using the API allows the runtime to take care of the runspace requirement by creating a new one every time we call the API. This simplifies the API user’s experience but comes with constraints and significant execution overhead.
Once the runspace is ready, you can create a [PowerShell] object and set the Runspace property on that object:
By setting the runspace on the [PowerShell] object, you let the runtime know to use that runspace for execution rather than create a new one. With the runspace assigned, add a script to the [PowerShell] object in $p and invoke it:
The script that’s passed assigns a value to the variable $x in the associated runspace and so returns no value. Now you’re going to execute another command in that runspace. You could create a new [PowerShell] object and associate the runspace, but let’s look at an alternative way of doing this. Rather than creating a new [PowerShell] object each time, you can reuse the existing object by clearing the Commands property on the object. This removes all the previously added commands so you can start from scratch adding new commands: