【问题标题】:Generically bind scriptblock parameters from array passed to ArgumentList将传递给 ArgumentList 的数组中的脚本块参数一般绑定
【发布时间】:2018-05-15 22:51:12
【问题描述】:

我希望能够以一种我事先不知道脚本块定义的参数的通用方式将对象数组的值绑定到脚本块的参数。例如:

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:鲍勃 20 史密斯 你好“鲍勃 20 史密斯”。您的年龄是:''并且您的姓氏是

【问题讨论】:

  • 作为后续,如何使以下内容起作用? test @{firstname="Bob";age="20";lastname="Smith"}

标签: powershell parameter-passing


【解决方案1】:

使用Splatting,如: & $sb @allargs

【讨论】:

  • 谢谢!这让我发疯了。我总是忘记喷溅。希望这已经打动了我的脑海。
【解决方案2】:

在脚本块上使用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'

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 2015-03-03
    • 2013-04-27
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多