Using Synchronized HashTables
Last month, I introduced you to the topic of creating and using PowerShell runspaces. This is definitely and advanced topic and for those special use cases where runspace-related commands like Start-Job
are lacking.
You might want to use a runspace to run continuous code in the background. With commands like Invoke-Command
or Start-Job
you can leverage runspaces to execute code in parallel. In PowerShell 7, you could also use the -Parallel
parameter with ForEach-Object
. However, in these situations, your code runs, exits, and you collect your results. You can create a runspace that doesn't end by running code in a loop. The challenge is that you can't really see into the runspace.
One intriguing possibility is the use of a special type of hashtable, called a synchronized hashtable. This is a hashtable that is shared between the runspace and the scope that launched the runspace. Because it is a hashtable, you can modify it on-the-fly. You can make any hashtable synchronized with syntax like this:
$syncHash = [hashtable]::Synchronized(@{})