🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Runspace Basics

A runspace is a separate space where PowerShell runs a command. It gives one block its own place to run, apart from the main script.

One runspace runs one block

A runspace is opened, then a block is linked to it. Invoke runs the block and returns its result.

$rs = [runspacefactory]::CreateRunspace()
$rs.Open()
$ps = [powershell]::Create()
$ps.Runspace = $rs
[void]$ps.AddScript('2 + 3')
$r = $ps.Invoke()
"Runspace: $r"
$ps.Dispose()
$rs.Close()
$rs.Dispose()

A runspace can take a value

A parameter carries a value into the block. The block doubles the value it receives.

$rs = [runspacefactory]::CreateRunspace()
$rs.Open()
$ps = [powershell]::Create()
$ps.Runspace = $rs
[void]$ps.AddScript('param($x) $x * 2').AddParameter("x", 21)
$r = $ps.Invoke()
"Doubled: $r"
$ps.Dispose()
$rs.Close()
$rs.Dispose()

A runspace can run without waiting

BeginInvoke starts the block and returns at once. EndInvoke collects the result when it is ready.

$rs = [runspacefactory]::CreateRunspace()
$rs.Open()
$ps = [powershell]::Create()
$ps.Runspace = $rs
[void]$ps.AddScript('4 + 5')
$async = $ps.BeginInvoke()
$r = $ps.EndInvoke($async)
"Async: $r"
$ps.Dispose()
$rs.Close()
$rs.Dispose()

Example

$rs = [runspacefactory]::CreateRunspace()
$rs.Open()
$ps = [powershell]::Create()
$ps.Runspace = $rs
[void]$ps.AddScript('param($a, $b) ($a * $a) + ($b * $b)').AddParameter("a", 3).AddParameter("b", 4)
$r = $ps.Invoke()
"Squares sum: $r"
$ps.Dispose()
$rs.Close()
$rs.Dispose()

Key points

  • Runspace: a separate space where PowerShell runs commands.
  • Use the runspace factory to make a new runspace.
  • Use Open to start a runspace before it runs anything.
  • Use a PowerShell object linked to the runspace to carry the block.
  • Use Invoke to run the block and collect its result.
  • Use Close and Dispose to clean up a runspace after use.

In this example, a runspace is made and opened first. A block with two parameters is linked to it, and Invoke runs it. The result is printed, then the runspace is cleaned up.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What must happen before a runspace runs a block?