Description
Documentation Issue
PowerShell Scopes documentation says this about using variables to "Thread jobs":
The
Using
scope modifier is supported in the following contexts:
- ...
- Thread jobs, started via
Start-ThreadJob
orForEach-Object -Parallel
(separate thread session)Depending on the context, embedded variable values are either independent copies of the data in the caller's scope or references to it.
...
In thread sessions, they are passed by reference. This means it is possible to modify call scope variables in a different thread. To safely modify variables requires thread synchronization.
To me, coming from C#/C++ background, passing by reference means that you can assign these variables and have the assigned value be available in the calling code.
Yet the following fails to run:
$foo = 1
Start-ThreadJob {
Write-Host $using:foo
$using:foo = 2
} | Wait-Job | Out-Null
Write-Host $foo
It errors on $using:foo = 2
with:
The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property.
I assume it's not a bug in PowerShell, but rather the documentation does not really correctly document how the variable can be modified. That the actual variable cannot be modified, but if one passes something like an object or a hash table, one can modify its fields/contents. I.e. it is conceptually more like passing a pointer to an object by value, rather then passing a variable by reference.
Context of the issue
Originally posted on Stack Overflow:
Modifying PowerShell $using scope variables in thread started with Start-ThreadJob