我运行时遇到错误Invoke-Command
其中脚本块采用字典类型的参数:
无法处理参数“字典”的参数转换。
无法转换类型的“System.Collections.Hashtable”值
输入“System.Collections.Hashtable”
“System.Collections.Generic.IDictionary`2[System.String,System.String]”。
行:7 字符:1
+ 调用命令-计算机名。 -ArgumentList $dictionary -ScriptBlock ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [], ParameterBindin...mationException
+ FullQualifiedErrorId : 参数参数转换错误
+ PS 计算机名 : 本地主机
经过大量挖掘后,我能够将脚本简化为下面的 MVP,以显示此问题的根源:
[System.Collections.Generic.IDictionary[string, string]]$dictionary = New-Object -TypeName 'System.Collections.Generic.Dictionary[string, string]'
$dictionary.Add('one', 'hello')
$dictionary.Add('two', 'world')
Write-Verbose "Main Script $($dictionary.GetType().FullName)" -Verbose #outputs: VERBOSE: Before System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Invoke-Command -ComputerName . -ArgumentList $dictionary -ScriptBlock {
Param (
#[System.Collections.Generic.IDictionary[string, string]] #if I leave this in I get a conversion error
$dictionary
)
Write-Verbose "Function before $($dictionary.GetType().FullName)" -Verbose #outputs: VERBOSE: After System.Collections.Hashtable
function Poc {} #this line seems to cause the `$dictionary` to become a HashTable
Write-Verbose "Function after $($dictionary.GetType().FullName)" -Verbose #outputs: VERBOSE: After System.Collections.Hashtable
}
看来如果脚本块为Invoke-Command
包含任何内联函数,则参数会自动转换为HashTable
;而如果脚本块不包含任何嵌套函数定义,则参数将保留为System.Collections.Generic.IDictionary[string, string]
.
我是否滥用了此功能/是否有常见的解决方法?或者这只是 PowerShell 中的一个错误?