PowerShell的错误返回哈希表
问题描述:
任何人有任何想法,为什么下面的代码会产生一个错误,详细信息请参阅PowerShell的错误返回哈希表
功能后附加注释function callee ([Hashtable]$arg0) {
[Hashtable]$hashtable = @{}
$hashtable = $arg0
$hashtable.add('passed', $True)
# $hashtable ######## toggle this line
$type = $hashtable.GetType()
Write-Host "$type"
return $hashtable
}
function caller {
[Hashtable]$hashtable = @{'00'='0'}
$hashtable = callee $hashtable ##### returns error here
$hashtable.add('returned', $True)
$hashtable
}
caller
错误消息: 不能转换“System.Object的[]”类型“System.Object []”的值键入“System.Collections.Hashtable”。
我收到各种实例的错误,我试图缩小到一个很容易重现的例子。它看起来像是将哈希表更改为对象数组,这就是为什么它不会返回它?它允许我修改哈希表并返回它,但是当我尝试显示它时,它会改变它?当我开始向被调用函数添加代码时,这与我获得的效果是一样的吗?
答
当你取消注释# $hashtable
你正在输出两个东西从函数。函数的结果是它的一切“输出”,PowerShell会自动将多个输出包装到一个数组中。 return语句是一个短路便利性,不应该与从函数返回值的唯一方法混淆。
类似的问题在这里http://stackoverflow.com/questions/2158786/calling-echo-inside-a-function-pre-pends-echo-string-to-return-value-in-powershel – 2010-09-19 03:59:27
同意。我建议不要在PowerShell中使用成语'return',因为它具有误导性。它在功能上等同于'Write-Output ; return'。最好把'$ hashtable'作为函数的最后一行,并称它很好(就像* caller *函数一样)。 –
2010-09-19 06:20:27