如何将脚本块作为启动作业中的参数之一传递 [英] How do I pass a scriptblock as one of the parameters in start-job
问题描述
我正在尝试创建一个执行脚本块的后台作业.我需要将此脚本块作为参数传递,但我似乎无法使语法起作用.脚本块正在沿途的某个地方转换为字符串.
I'm trying to create a background job, which executes a scriptblock. I need to pass this scriptblock in as a parameter, but I can't seem to get the syntax to work. The scriptblock is being converted to a string somewhere along the way.
当我将脚本块传递给本地函数时它工作正常,但不能通过 start-job
It works fine when I pass the script block to a local function, but not through start-job
以下语法有效:
function LocalFunction
{
param (
[parameter(Mandatory=$true)]
[ScriptBlock]$ScriptBlock
)
&$ScriptBlock | % { echo "got $_" }
}
LocalFunction -ScriptBlock { echo "hello" }
这会按预期输出got hello".
This outputs "got hello" as expected.
但以下失败:
$job = start-job -argumentlist { echo "hello" } -scriptblock {
param (
[parameter(Mandatory=$true)]
[ScriptBlock]$ScriptBlock
)
&$ScriptBlock | % { echo "got $_" }
}
start-sleep -s 1
receive-job $job
返回的错误是
Receive-Job : Cannot process argument transformation on parameter 'ScriptBlock'. Cannot convert the " echo "hello" " value of type "System.String" to type "System.Management.Automation.ScriptBlock".
因此,如果我正确地阅读了错误,似乎 -argumentlist 以某种方式将其参数强制转换为字符串.
So if I'm reading the error right, it appears that -argumentlist is somehow forcing its arguments into strings.
任何 powershell 专家都知道如何使这种语法起作用?
Any powershell gurus know how to make this syntax work?
提前致谢,
本
推荐答案
这里有一个方法可以解决这个问题,将脚本块代码作为字符串传递,然后从作业内部的字符串创建一个脚本块并执行
Here's one way to solve this, pass the scriptblock code as a string, then create a scriptblock from the string inside the job and execute it
Start-Job -ArgumentList "write-host hello" -scriptblock {
param (
[parameter(Mandatory=$true)][string]$ScriptBlock
)
& ([scriptblock]::Create($ScriptBlock))
} | Wait-Job | Receive-Job
这篇关于如何将脚本块作为启动作业中的参数之一传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!