execute common scriptblock when invoking new runspace?

Welcome Forums General PowerShell Q&A execute common scriptblock when invoking new runspace?

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
1 year, 3 months ago.

  • Author
    Posts
  • #73945

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

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

  • #73972

    Participant
    Points: 0
    Rank: Member

    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)
    #[...] 
    

The topic ‘execute common scriptblock when invoking new runspace?’ is closed to new replies.