Powershell错误返回哈希表 [英] Powershell error returning hashtable
问题描述
任何人都知道为什么以下代码会产生错误,请在函数后查看其他注释以获取更多详细信息
Anyone have any ideas why the following code would produce an error, see additional comments after the function for more details
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".
error message: Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Hashtable".
我在各种情况下都收到错误,我尝试将其范围缩小到一个易于重现的示例.看起来它正在将哈希表更改为对象数组,这就是为什么它不返回它的原因?它允许我修改哈希表并返回它,但是当我尝试显示它时,它会改变吗?当我开始向被调用者函数中添加代码时,会得到相同的效果吗?
I receive the error on a variety of instances, I tried to narrow it down to an example that is easy to reproduce. It looks like it is changing the hashtable to an object array and that is why it won't return it? It allows me to modify the hashtable and return it but when I try to display it it changes it? This is the same effect I get when I start adding code to the callee function?
推荐答案
取消注释# $hashtable
时,您将从函数中输出两件事.该函数的结果是该函数的所有输出",PowerShell将自动将多个输出包装到一个数组中. return语句是一种短路便利,不应与从函数返回值的唯一方法相混淆.
When you uncomment # $hashtable
you're outputting two things from the function. The result of the function is everything 'output' from it, and PowerShell will automatically wrap multiple outputs into an array. The return statement is a short-circuit convenience and should not be confused with the only way to return a value from the function.
这篇关于Powershell错误返回哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!