execute common scriptblock when invoking new runspace?

Hey all,

Im trying to figure out how to setup a scriptblock that defines a bunch of mixed data (functions, variables) and then import & execute it into newly created runspaces. $sharedData gets imported, but it doesnt look like its executing and defining $myvariable inside the new runspace.


$syncHash = [hashtable]::Synchronized(@{})

$sharedData = {$Myvariable = “wootwoot”}

$RunSpaceNew =[runspacefactory]::CreateRunspace()
$RunSpaceNew.ApartmentState = “STA”
$RunSpaceNew.ThreadOptions = “UseNewThread”
$PScode_to_RunNew = [PowerShell]::Create()

& $shareddata;
invoke-expression $shareddata;

$synchash.test = $Myvariable

$PScode_to_RunNew.Runspace = $RunSpaceNew
$handleNew = $PScode_to_RunNew.BeginInvoke()

your variable assignment $Myvariable = “wootwoot”
happen inside scriptblock thus, it assigns local $Myvariable, not available when you $synchash.test = $Myvariable

if you just want use runspaces you can use PoshRSJob module

but if you really need such difficult way you can pass your variables by reference inside scriptblock

$syncHash = [hashtable]::Synchronized(@{})

$sharedData = {param([ref]$Myvariable) $Myvariable.value = "wootwoot" }

$myvariable = 'default value'
& $shareddata ([ref]$Myvariable)