![](/img/trans.png)
[英]Javac splatting operator '@' cannot be used in Powershell and cmd
[英]Powershell splatting operator only for accepted parameters?
當哈希表包含該函數接受的更多條目時,是否有可能使用PowerShell從哈希表使用splatting?
我的用例是讓配置對象從一個函數傳遞給另一個函數。 但是,所有功能均不需要相同的參數。
例如:
function Process-Something{
param(
[Parameter()]
[string]$Owner
)
}
function Process-SomethingElse{
param(
[Parameter()]
[string]$Owner,
[Parameter()]
[int]$x,
[Parameter()]
[int]$y
)
}
$config = @{
"Owner" = "Bart Simpson"
"X" = 10
"Y" = 20
}
Process-Something @config
Process-SomethingElse @config
它因以下錯誤而失敗:
Process-Something : Cannot find a matching parameter « Y ».
這樣做的目的是避免為每個函數指定單獨的屬性。
正如@Ansgar在評論中指出的那樣,定義參數的整個想法是要進行驗證。 將參數放置到函數中時,就是要強制它們使用函數。 因此,如果哈希表的給定屬性不作為參數存在,您將得到一個錯誤-就像預期的那樣。
您可以做的是進入PSCustomObject並利用管道。 如果使用屬性名稱( ValueFromPipelineByPropertyName = $true
)將所有參數設置為接受管道中的值,則實際上可以得到所需的行為。
首先,我將重新定義您的不同功能,以配置ValueFromPipelineByPropertyName = $true
參數屬性。
function Process-Something{
param(
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]$Owner
)
$PSBoundParameters
}
function Process-SomethingElse{
param(
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]$Owner,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[int]$x,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[int]$y
)
$PSBoundParameters
}
有了它,我就可以像您的示例一樣創建一個哈希表,將其轉換為PSCustomObject,現在我可以將該新對象通過管道傳遞給不同的方法,並讓它們僅選擇所需的屬性。
我包括了PSBoundParameters
來展示它們得到了他們期望的結果。 測試是這樣完成的:
$config = @{
"Owner" = "Bart Simpson"
"X" = 10
"Y" = 20
}
$psConfig = [PSCustomObject]$config
$psConfig | Process-Something
$psConfig | Process-SomethingElse
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.