我希望能够以通用的方式将对象数组的值绑定到scriptblock的参数,而我事先并不知道scriptblock定义的参数。例如:
function test {
Param([object[]] $allargs)
Write-Host "allargs: $allargs"
$sb = {
param($firstname, $age, $lastname)
Write-Host "Hello `"$firstname`". Your age is: '$age' and your last name is $lastname"
}
& $sb $allargs
}
cls
test "Bob","20","Smith"
输出:
allargs: Bob 20 Smith Hello "Bob 20 Smith". Your age is: '' and your last name is
答案 0 :(得分:1)
使用Splatting,如下所示:
& $sb @allargs
答案 1 :(得分:0)
在scriptblock上使用automatic variable $args
,splat,并使用3个不同的参数调用您的函数,而不是一个数组参数:
function test {
Write-Host "allargs: $args"
$sb = {
Param($firstname, $age, $lastname)
Write-Host "Hello '${firstname}'. Your age is: '${age}' and your last name is '${lastname}'"
}
& $sb @args
}
test 'Bob' '20' 'Smith'