I'm having trouble understanding how GetNewClosure works in conjunction with Start-Job. Case in point I have the following code
function Test([string]$Name)
{
$block = { Write-Host "Name = $Name" }.GetNewClosure()
&$block
Other $block
OtherJob $block
}
function Other([scriptblock]$Block)
{
Write-Host -NoNewline "In Other: "
&$Block
}
function OtherJob([scriptblock]$Block)
{
Write-Host -NoNewline "In OtherJob: "
$j = Start-Job -ScriptBLock $Block
Start-Sleep -s 1
$j | Receive-Job
}
When calling the code I get
PS C:\> Test "foo"
Name = foo
In Other: Name = foo
In OtherJob: Name =
Notice that $Name is not captured in OtherJob.
It is probably related to Start-Job starting a new PS instance, but is there any workaround for this (Preferably one that does not include using -ArgumentList)?
PS: The version table should it matter
PS C:\> $PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.5485
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1