Skip to content

Instantly share code, notes, and snippets.

@sunnyc7
Last active November 27, 2020 23:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunnyc7/04a285bafd56d89d4bac to your computer and use it in GitHub Desktop.
Save sunnyc7/04a285bafd56d89d4bac to your computer and use it in GitHub Desktop.
Sharing state across different runspaces using a shared variable
# Sharing state across different runspaces using a shared variable
# Expirmenting with Boe's stuff
# http://learn-powershell.net/2013/04/19/sharing-variables-and-live-objects-between-powershell-runspaces/
# Create a synhronized HashTable which will be shared across different runspaces
$hash = [hashtable]::Synchronized(@{})
$hash.one = 1
# You can also create a non-synchronized hashtable, and that will work too. (i.e. Can be used to share state across runspaces)
$hash = [hashtable]::new()
$hash.one = 1
# Runspace One
$rs1 = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()
$rs1.open()
$rs1.SessionStateProxy.SetVariable('Hash',$hash)
# Powershell Instance One
$ps1 = [powershell]::Create()
$ps1.runspace = $rs1
$ps1.AddScript(
{$hash.one++}
)
# ScriptBlock which will execute the PS Instance ONE
$sb1 = {
$hash.one
$ps1.BeginInvoke()
}
# Runspace Two
$rs2 = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()
$rs2.open()
$rs2.SessionStateProxy.SetVariable('Hash',$hash)
# Powershell Instance Two
$ps2 = [powershell]::Create()
$ps2.runspace = $rs2
$ps2.AddScript(
{$hash.one++}
)
# ScriptBlock which will execute the PS Instance TWO
$sb2= {
$hash.one
$ps2.BeginInvoke()
}
# Hash Value Before executing the PS Instance
$hash.one
# Call the scriptblock ONE, which executes Instance PS1 for RS1
& $sb1
$hash.one
# Call the scriptblock TWO, which executes Instance PS2 for RS2
& $sb2
$hash.one
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment