The code below will demonstrate usage of the Synchronized variable for Runspaces. You can use any ip/hostname for $ComputerName as long it’s accessible, Powershell remoting is verified by Enter-PSSession and also you added credential to Windows Credential Manager for $ComputerName as host.
Get-Runspace | ? Id -NE 1 | % { $_.close() ; $_.dispose() } $Runspace = $powerShell = $connectionInfo = $handle = $hash = $null $ComputerName = '192.168.0.3' $hash = [hashtable]::Synchronized(@{}) $hash.One = 1 Write-host ('Value of $Hash.One before background runspace is {0}' -f $hash.one) -ForegroundColor Green -BackgroundColor Black $Uri = New-Object System.Uri("http://$($ComputerName):5985/wsman") $connectionInfo = New-Object System.Management.Automation.Runspaces.WSManConnectionInfo -ArgumentList $Uri $connectionInfo.AuthenticationMechanism = [System.Management.Automation.Runspaces.AuthenticationMechanism]::Negotiate $connectionInfo.OpenTimeout = 3000 $Runspace = [runspacefactory]::CreateRunspace($connectionInfo) # don't work #$Runspace = [runspacefactory]::CreateRunspace() # works $runspace.Open() $runspace.SessionStateProxy.SetVariable('Hash',$hash) $powershell = [powershell]::Create() $powershell.Runspace = $runspace $powershell.AddScript({ $hash.one++ }) | Out-Null #The Out-Null at the end is used to prevent the output of the object that occurs. $handle = $powershell.BeginInvoke() While (-Not $handle.IsCompleted) { Start-Sleep -Milliseconds 100 } $powershell.EndInvoke($handle) $runspace.Close() $powershell.Dispose()
Write-host (‘Value of $Hash.One after background runspace is {0}’ -f $hash.one) -ForegroundColor Green -BackgroundColor Black
As soon as I replace:
$Runspace = [runspacefactory]::CreateRunspace()
with
$Runspace = [runspacefactory]::CreateRunspace($connectionInfo)
(because I want to execute code at the remote computer), the synchronized variable $hash is not updated. Anyone know what I missing? This feature is really important and useful and I need it to make it work for remote runspaces.