Skip to content

Instantly share code, notes, and snippets.

@dlwyatt
Created April 12, 2014 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlwyatt/ef63876c26c90d082f95 to your computer and use it in GitHub Desktop.
Save dlwyatt/ef63876c26c90d082f95 to your computer and use it in GitHub Desktop.
Demonstrating how to set up a RunspacePool with access to module commands, and shared access to .NET objects.
# $arrayList is the object I want to share across runspaces.
$arrayList = New-Object System.Collections.ArrayList
$sessionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
# Calling ImportPSModule("PSThreading") requires that the module be installed on the PSModulePath. The
# method can also accept a file system path directly to a psd1, psm1 or dll file, such as
# $sessionState.ImportPSModule("$pwd\PSThreading.psm1")
$sessionstate.ImportPSModule("PSThreading")
# Sharing variables this way requires the creation of SessionStateVariableEntry objects. The third argument to
# the constructor of this type is a "Description" field, but appears to be optional. I've passed in both
# $null and [NullString]::Value for the third argument, without encountering any errors.
$sessionstate.Variables.Add(
(New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('arrayList', $arrayList, $null))
)
$runspacepool = [runspacefactory]::CreateRunspacePool(1, 2, $sessionstate, $Host)
$runspacepool.Open()
# Now, the runspace pool is ready for use by PowerShell objects that will have access to my $arrayList variable
# and the Lock-Object function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment