我可以直接将这些参数分别以正确的类型仅值导入到我的函数中吗?
$appparams = @{
sname = "RandomAppName" # type: string
sdata = [byte]12 # type: Byte
sgroup = $null # type: NULL
}
案例:未分别发送+类型不正确
$arglist = ($appparams.GetEnumerator() | Sort-Object Name | % { "$($_.Value)" }) -join ','
Invoke-Function .... $arglist -> Invoke-Function .... 12,,RandomAppName
预期:仅发送分别具有且没有任何插值的值
Invoke-Function .... $arglist -> Invoke-Function .... "RandomAppName",12,$null
看起来您正在尝试将 hashtable 条目的 values 作为 positional 参数传递给
Invoke-Function
这与通常使用 named 参数的基于 hashtable 的 splatting 形成对比,其中每个条目的 key 表示目标参数,以及 value 参数。
换句话说:
Invoke-Function @appParams
仅在Invoke-Function
声明名为-sname
、-sdata
和-sgroup
且具有匹配数据类型的参数时才有效。
首先,正如 mclayton 指出的那样,如果必须维护条目(值)的定义顺序,则需要一个 ordered 哈希表 (
[ordered]
):
然后您可以使用基于数组的splatting来位置传递哈希表的值:
# Sample function that echoes its positional arguments:
function Foo { $args | ForEach-Object { $isNull = $null -eq $_; [pscustomobject] @{ Value = if ($isNull) { '$null' } else { $_ }; Type = if (-not $isNull) { $_.GetType() } } } }
# The ordered hashtable whose values are to be passed as positional arguments.
$appParams = [ordered] @{
sname = "RandomAppName" # type: string
sdata = [byte]12 # type: Byte
sgroup = $null # type: NULL
}
# Get the ordered hashtable's values, as an *array*.
$appParamValues = $appParams.Values
# Pass the values as separate, positional arguments.
Foo @appParamValues
输出:
Value Type
----- ----
RandomAppName System.String
12 System.Byte
$null