[英]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.