Invoke-Command
在脚本块采用字典类型参数的情况下,我一直在运行错误:
无法处理参数“字典”上的参数转换。无法将“System.Collections.Hashtable”类型的“System.Collections.Hashtable”值转换为“System.Collections.Generic.IDictionary`2[System.String,System.String]”类型。在 line:7 char:1 + Invoke-Command -ComputerName 。-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 中的一个错误?