concept runspace in category powershell

appears as: runspace, runspaces, runspace, A runspace, runspaces
Windows PowerShell in Action, Third Edition

This is an excerpt from Manning's book Windows PowerShell in Action, Third Edition.

PS> Invoke-Command -Session $s -ScriptBlock { & {Get-Date}}
The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode.

PS> Invoke-Command -Session $s -ScriptBlock {function MyGetDate { [string] (Get-Date) }; MyGetDate}
The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode.

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:

PS> $p = [PowerShell]::Create()
PS> $p.Runspace = $rs

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:

PS> $p.AddScript{$x = 123}.Invoke()

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:

PS> $p.Commands.Clear()

Now add a new script to return the value assigned to $x in the runspace you created. This will verify that its value is what you set it to in the first command:

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest