Powershell Start-Job调用带有参数的函数参数 [英] Powershell Start-job invoke function argument with parameter
问题描述
我有一个具有两个参数的函数mainFunction
-$name
将只是一个常规字符串,而$moveFunction
将是一些函数.
I have a function mainFunction
that gets 2 parameters - $name
will be just a regular string, and $moveFunction
will be some function.
我想开始一个ScriptBlock($SB
)的工作,该脚本将以$name
作为参数来调用$moveFunction
.
I want to start a job of a ScriptBlock ($SB
) that will invoke $moveFunction
with $name
as his argument.
function foo($a){
Write-Output "In function foo with the argument => $a"
}
$SB = {
param($C, $fooFunction)
$fooFunction.Invoke($C)
}
function mainFunction($name, $moveFunction){
Start-Job -Name "currentJob" -ArgumentList $name, ${Function:$moveFunction} -ScriptBlock $SB
}
$j1 = mainFunction -name "output!" -moveFunction $Function:foo
我检查mainFunction
中是否已经存在$moveFunction
(在mainFunction
处的$moveFunction.invoke(5)
)
I checked that $moveFunction
exists in mainFunction
already ($moveFunction.invoke(5)
at mainFunction
)
在开始工作时将函数作为参数传递时,我找不到问题.
I can't find the problem in passing the function as argument in the start-job.
,然后从Get-Job -Name "CurrentJob" | Receive-Job
我得到:
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : localhost
任何帮助将不胜感激.
Any help would be appreciated.
问题很可能是我将函数作为参数传递的方式(${Function:$moveFunction}
edit:
The problem is most likely the way I pass the function as an argument (${Function:$moveFunction}
推荐答案
仅是对我之前的注释和代码示例进行了重新混编.类似的问题此处.本质上,传递给Jobs和Remote命令的参数是序列化的.在反序列化过程中,函数和脚本块以字符串形式出现,而不是其原始类型.幸运的是,使用[ScriptBlock]::Create("string")
将它们转换为可调用的脚本块是一个简单的过程.
Just a rehash of my previous comment plus code example. Similar issue here. Essentially, arguments passed to Jobs and Remote commands are serialized. During the de-serialization process, functions and script blocks come out as strings instead of their original type. Fortunately it's a simple process to transform these into invokable scriptblocks using [ScriptBlock]::Create("string")
.
function foo {
write-host "foo"
}
function bar {
# This argument comes in as a string
param($func)
write-host "bar"
# Create scriptblock from string
$func = [ScriptBlock]::Create($func)
$func.invoke()
}
Start-Job -ArgumentList $Function:Foo -ScriptBlock $Function:Bar
Get-Job | Wait-job
Get-Job | Receive-job
这篇关于Powershell Start-Job调用带有参数的函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!