execute common scriptblock when invoking new runspace?

This topic contains 2 replies, has 2 voices, and was last updated by  Max Kozlov 3 months, 3 weeks ago.

  • Author
    Posts
  • #73945

    Arthur K
    Participant

    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.

    example:

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

    $sharedData = {$Myvariable = "wootwoot"}

    $RunSpaceNew =[runspacefactory]::CreateRunspace()
    $RunSpaceNew.ApartmentState = "STA"
    $RunSpaceNew.ThreadOptions = "UseNewThread"
    $RunSpaceNew.Open()
    $RunSpaceNew.SessionStateProxy.SetVariable("syncHash",$syncHash)
    $RunSpaceNew.SessionStateProxy.SetVariable("sharedData",$sharedData)
    $PScode_to_RunNew = [PowerShell]::Create()
    $PScode_to_RunNew.AddScript({

    & $shareddata;
    invoke-expression $shareddata;

    $synchash.test = $Myvariable

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

  • #73970

    Max Kozlov
    Participant

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

  • #73972

    Max Kozlov
    Participant

    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.