簡體   English   中英

在Powershell中通過引用傳遞hashtable之后進行Splatting

[英]Splatting after passing hashtable by reference in Powershell

當我通過參考一個用於splatting目的的函數傳遞哈希表時,我遇到了麻煩。 我怎樣才能解決這個問題?

Function AllMyChildren {
    param (
        [ref]$ReferenceToHash
    }
    get-childitem @ReferenceToHash.Value
    #  etc.etc.
}
$MyHash = @{
    'path' = '*'
    'include' = '*.ps1'
    'name' = $null
}
AllMyChildren ([ref]$MyHash)

結果:錯誤( “Splatted變量不能用作屬性或數組表達式的一部分。將表達式的結果分配給臨時變量,然后改為映射臨時變量。” )。

試圖這樣做:

$newVariable = $ReferenceToHash.Value
get-childitem @NewVariable

這確實有效,並且根據錯誤消息似乎正確。 在這種情況下它是首選語法嗎?

1)使用[ref]傳遞哈希表(或類的任何實例,即引用類型)是沒有意義的,因為它們總是通過引用本身傳遞。 [ref]與值類型(標量和結構實例)一起使用。

2)splatting操作符可以直接應用於變量,而不是表達式。

因此,為了解決問題,只需按原樣傳遞函數中的哈希表:

Function AllMyChildren {
    param (
        [hashtable]$ReferenceToHash # it is a reference itself
    )
    get-childitem @ReferenceToHash
    #  etc.etc.
}
$MyHash = @{
    'path' = '*'
    'include' = '*.ps1'
    'name' = $null
}
AllMyChildren $MyHash

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM