将哈希表作为参数传递给 PowerShell 中的函数 [英] Passing a hashtable as an argument to a function in PowerShell
问题描述
我在 PowerShell 脚本中遇到问题:
I have a problem in a PowerShell script:
当我想将一个哈希表传递给一个函数时,这个哈希表不被识别为一个哈希表.
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
为什么?
推荐答案
$Input
是一个 自动变量 枚举给定的输入.
$Input
is an automatic variable that enumerates the input given.
选择任何其他变量名称,它就会起作用 - 尽管不一定如您所愿 - 要获取哈希表中的条目数,您需要检查 Count
属性:
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:
function Get-Length {
param(
[hashtable]$Table
)
$Table.Count
}
Write-Output
当您保持 $Table.Count
原样时隐含.
Write-Output
is implied when you just leave the $Table.Count
as is.
此外,当您使用 Param()
内联声明参数时,函数名称中的 ()
后缀是不必要的语法糖,其含义为零 - 删除它
Also, the ()
suffix in the function name is unnecessary syntactic sugar with zero meaning when you declare your parameters inline with Param()
- drop it
这篇关于将哈希表作为参数传递给 PowerShell 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!