execute common scriptblock when invoking new runspace?

This topic contains 2 replies, has 2 voices, and was last updated by  Max Kozlov 1 year ago.

  • Author
  • #73945

    Arthur K

    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()

  • #73970

    Max Kozlov

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

  • #73972

    Max Kozlov

    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)

You must be logged in to reply to this topic.