简体   繁体   English

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

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

I have a problem in a PowerShell script: 我在PowerShell脚本中遇到问题:

When I want to pass a Hashtable to a function, this hashtable is not recognized as a 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

Why? 为什么?

$Input is an automatic variable that enumerates the input given. $Input是一个自动变量 ,它枚举给定的输入。

Chose any other variable name and it'll work - although not necessarily as you might expect - to get the number of entries in a hashtable you need to inspect the Count property: 选择任何其他变量名称,它将起作用 -尽管不一定像您期望的那样-获取哈希表中的条目数,您需要检查Count属性:

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

    $Table.Count
}

Write-Output is implied when you just leave the $Table.Count as is. 仅将$Table.Count原样时,将隐含Write-Output

Also, the () suffix in the function name is unnecessary syntactic sugar with zero meaning when you declare your parameters inline with Param() - drop it 另外,函数名称中的()后缀是不必要的语法糖,具有零含义,当您使用Param()内联声明参数时-将其删除

I'm not really sure what to comment here, it seems self-explanatory. 我不太确定在这里要评论什么,这似乎是不言而喻的。 If not, leave a comment and I'll clarify. 如果没有,请发表评论,我会澄清。

$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"]

Output: 输出:

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