我想将ScriptBlock作为参数传递给Start Job ScriptBlock。我明白
[ScriptBlock]
在传递到作业时,为了安全起见,被序列化为字符串。所以,我需要反序列化它。我已经尝试过使用
[ScriptBlock]::Create()
但它似乎没有处理
$($args[0].cheese)
正确地。
这是我正在做的事情的简化版本。
function Format-Text {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)][Object]$InputObject,
[Parameter(Mandatory)][ScriptBlock]$Formatter)
Write-Host ($Formatter.Invoke($InputObject))
}
$formatter = {"My favourite cheese is: $($args[0].cheese)"}
$testObject = [PSCustomObject]@{cheese = 'cheddar'}
Format-Text -InputObject $testObject -Formatter $formatter
$job = Start-Job -ArgumentList $testObject,$formatter.ToString() -ScriptBlock {
param ([String]$Obj,
[String]$Fmtr)
function Format-Text {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)][Object]$InputObject,
[Parameter(Mandatory)][ScriptBlock]$Formatter)
Write-Host ($Formatter.Invoke($InputObject))
}
$sb = [ScriptBlock]::Create($Fmtr)
Format-Text -InputObject $Obj -Formatter $sb
}
do { Start-Sleep -Milliseconds 500 } until ($job.State -ne 'Running')
Receive-Job $job; Remove-Job $job
输出为:
My favourite cheese is: cheddar
My favourite cheese is:
我如何反序列化
string
使得
$($args[0].奶酪)
作品?
上面的例子被简化为骨架,真正的脚本是00行和许多函数。如果可以避免的话,我不想重写这个函数,因为它在许多其他地方都有使用。
我正在运行内置的PowerShell 5.1。