![](/img/trans.png)
[英]PowerShell 5.1 Can someone please explain hashtable and splatting
[英]PowerShell 5.1 Can receiving function signature contain splatting parameter?
PowerShell 5.1
你能在接收函數的簽名中定義一個噴濺參數嗎?
function main {
$test = @{p1='a';p2='b'}
DoWork @test
}
function DoWork {
param([?] @test) # line in question
# Maybe call another function with it
DoWork2 @test
}
main
我相信您正在尋找的是將用於DoWork
的相同參數傳遞給DoWork2
,如果是這種情況,您可以為此使用自動變量$PSBoundParameters
。
function DoWork {
[cmdletbinding()]
param($p1, $p2, $p3, $p4)
DoWork2 @PSBoundParameters
}
function DoWork2 {
[cmdletbinding()]
param($p1, $p2, $p3, $p4)
"'{0}' was called with the following parameters:" -f $MyInvocation.MyCommand.Name
$PSBoundParameters.Keys | ForEach-Object {
'Parameter: {0} // Argument: {1}' -f $_, $PSBoundParameters[$_]
}
}
下面是一個如何工作的最小示例:
PS /> DoWork a b c d
'DoWork2' was called with the following parameters:
Parameter: p1 // Argument: a
Parameter: p2 // Argument: b
Parameter: p3 // Argument: c
Parameter: p4 // Argument: d
PS /> DoWork -p4 hello -p2 world
'DoWork2' was called with the following parameters:
Parameter: p4 // Argument: hello
Parameter: p2 // Argument: world
重要的是要理解,要使其正常工作,兩個函數必須共享相同的參數名稱或與調用者的相同參數匹配的別名屬性聲明,即:
param($p1, $p2, $p3, [alias('p4')] $somethingelse)
還值得注意的是[cmdletbinding()]
屬性和/或[parameter()]
屬性聲明將使您的函數充當高級函數。 如果您嘗試綁定到高級函數的不存在參數,您將獲得ParameterBindingException作為結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.