通常绑定传递给ArgumentList

时间:2018-05-15 22:51:13

标签: powershell parameter-passing

我希望能够以通用的方式将对象数组的值绑定到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 

2 个答案:

答案 0 :(得分:1)

使用Splatting,如下所示: & $sb @allargs

答案 1 :(得分:0)

在scriptblock上使用automatic variable $argssplat,并使用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'