Powershell 无法将哈希表作为函数参数传递
在下面的代码中,我试图将哈希表传递到函数中,但它总是将其类型更改为对象[]Powershell 无法将哈希表作为函数参数传递,powershell,Powershell,在下面的代码中,我试图将哈希表传递到函数中,但它总是将其类型更改为对象[] function Show-Hashtable{ param( [Parameter(Mandatory = $true)][Hashtable] $input ) return 0 } function Show-HashtableV2{ param( [Parameter(Mandatory = $true)][r
function Show-Hashtable{
param(
[Parameter(Mandatory = $true)][Hashtable] $input
)
return 0
}
function Show-HashtableV2{
param(
[Parameter(Mandatory = $true)][ref] $input
)
write-host $input.value.GetType().Name
return 0
}
[Hashtable]$ht=@{}
$ht.add( "key", "val" )
# for test
[int]$x = Show-HashtableV2 ([ref]$ht)
# main issue
[int]$x = Show-Hashtable $ht.clone()
上面我尝试了使用$ht.Clone()
而不是$ht
,但没有成功
我得到的是:
Object[]
Show-Hashtable : Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Hashtable".
At C:\_PowerShellRepo\Untitled6.ps1:26 char:11
+ [int]$x = Show-Hashtable $ht #.clone()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Show-Hashtable], PSInvalidCastException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException,Show-Hashtable
我在问你该往哪个方向看。我的代码怎么了?$input
是一个包含枚举器的函数,枚举传递给函数的所有输入。您的参数名称与此冲突(我想知道为什么PowerShell在这种情况下不输出警告)
解决方案很简单,只需以不同的方式命名参数即可。g<代码>输入对象:
function Show-HashtableV2{
param(
[Parameter(Mandatory = $true)][ref] $InputObject
)
write-host $InputObject.value.GetType().Name
return 0
}
现在,该函数将打印
System.Collections.Hashtable
是的,很遗憾,PowerShell没有阻止为只读自动变量赋值-请参阅以获取背景信息。