GetNewClosure 和 Start-Job
GetNewClosure and Start-Job
我无法理解 GetNewClosure 如何与 Start-Job 结合使用。举个例子,我有以下代码
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
}
调用代码时我得到
PS C:\> Test "foo"
Name = foo
In Other: Name = foo
In OtherJob: Name =
请注意,$Name 未在 OtherJob 中捕获。
这可能与 Start-Job 启动一个新的 PS 实例有关,但是否有任何解决方法(最好是不包括使用 -ArgumentList 的解决方法)?
PS:版本 table 应该重要
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
多一点谷歌搜索产生了一个潜在的解决方法,取自
Powershell - how to pre-evaluate variables in a scriptblock for Start-Job
基本上可以用
$otherBlock = [scriptblock]::Create("Write-Host 'Name = $Name'")
OtherJob $otherBlock
或者在-InitializationScript中设置变量
我无法理解 GetNewClosure 如何与 Start-Job 结合使用。举个例子,我有以下代码
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
}
调用代码时我得到
PS C:\> Test "foo"
Name = foo
In Other: Name = foo
In OtherJob: Name =
请注意,$Name 未在 OtherJob 中捕获。
这可能与 Start-Job 启动一个新的 PS 实例有关,但是否有任何解决方法(最好是不包括使用 -ArgumentList 的解决方法)?
PS:版本 table 应该重要
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
多一点谷歌搜索产生了一个潜在的解决方法,取自
Powershell - how to pre-evaluate variables in a scriptblock for Start-Job
基本上可以用
$otherBlock = [scriptblock]::Create("Write-Host 'Name = $Name'")
OtherJob $otherBlock
或者在-InitializationScript中设置变量