将哈希表作为参数传递给PowerShell中的函数

Als*_*ian 9 powershell

我在PowerShell脚本中遇到问题:

当我想将Hashtable传递给函数时,此哈希表不会被识别为哈希表.

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
Run Code Online (Sandbox Code Playgroud)

为什么?

Mat*_*sen 16

$Input是一个自动变量,枚举给定的输入.

选择任何其他变量名称,它将起作用 - 尽管不一定如您所料 - 获取哈希表中的条目数量,您需要检查该Count属性:

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

    $Table.Count
}
Run Code Online (Sandbox Code Playgroud)

Write-Output当你离开现状时隐含着$Table.Count.

此外,()当您声明参数内联时,函数名称中的后缀是不必要的语法糖,其含义为零Param()- 删除它


M H*_*M H 5

我不太确定在这里评论什么,这似乎是不言自明的。如果没有,请发表评论,我会澄清。

$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"]
Run Code Online (Sandbox Code Playgroud)

输出:

One is ... 
the loneliest number
Two is ... 
just as bad as one
Run Code Online (Sandbox Code Playgroud)