【发布时间】:2019-12-25 15:06:27
【问题描述】:
我在运行 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 + FullyQualifiedErrorId : ParameterArgumentTransformationError + PSComputerName : 本地主机
经过大量挖掘,我能够将脚本简化为下面的 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 中的一个错误?
【问题讨论】:
-
哇哦。我一直认为这是一个核心的 PS 问题。但从来没有想过一个错误。 mkelement0 巧妙地回答了这个问题,我的建议是永久储存这个问题。提请版主注意冻结此问题。这是可以帮助所有人的核心 PS 缺陷之一。感谢您的努力
标签: powershell dictionary hashtable psobject powershell-v5.1