簡體   English   中英

將哈希表作為參數傳遞給PowerShell中的函數

[英]Passing a hashtable as an argument to a function in PowerShell

我在PowerShell腳本中遇到問題:

當我想將哈希表傳遞給函數時,該哈希表不被識別為哈希表。

function getLength(){
    param(
        [hashtable]$input
    )

    $input.Length | Write-Output
}

$table = @{};

$obj = New-Object PSObject;$obj | Add-Member NoteProperty Size 2895 | Add-Member NoteProperty Count 5124587
$table["Test"] = $obj


$table.GetType() | Write-Output ` Hashtable
$tx_table = getLength $table `Unable to convert System.Collections.ArrayList+ArrayListEnumeratorSimple in System.Collections.Hashtable

為什么?

$Input是一個自動變量 ,它枚舉給定的輸入。

選擇任何其他變量名稱,它將起作用 -盡管不一定像您期望的那樣-獲取哈希表中的條目數,您需要檢查Count屬性:

function Get-Length {
    param(
        [hashtable]$Table
    )

    $Table.Count
}

僅將$Table.Count原樣時,將隱含Write-Output

另外,函數名稱中的()后綴是不必要的語法糖,具有零含義,當您使用Param()內聯聲明參數時-將其刪除

我不太確定在這里要評論什么,這似乎是不言而喻的。 如果沒有,請發表評論,我會澄清。

$ExampleHashTable = @{
    "one" = "the loneliest number"
    "two" = "just as bad as one"
}

Function PassingAHashtableToAFunctionTest {
    param(
        [hashtable] $PassedHashTable,
        [string] $AHashTableElement
    )

    Write-Host "One is ... " 
    Write-Host $PassedHashTable["one"]
    Write-Host "Two is ... " 
    Write-Host $AHashTableElement
}

PassingAHashtableToAFunctionTest -PassedHashTable $ExampleHashTable `
    -AHashTableElement $ExampleHashTable["two"]

輸出:

One is ... 
the loneliest number
Two is ... 
just as bad as one

暫無
暫無

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

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