【问题标题】:Create new System.Collections.Generic.Dictionary object fails in PowerShell在 PowerShell 中创建新的 System.Collections.Generic.Dictionary 对象失败
【发布时间】:2019-11-13 09:22:34
【问题描述】:

PowerShell 版本:5.x、6

我正在尝试创建System.Collections.Generic.Dictionary 的新对象,但它失败了。

我尝试了以下“版本”:

> $dictionary = new-object System.Collections.Generic.Dictionary[[string],[int]]
New-Object : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ComObject'. Specified method is not supported.
At line:1 char:25
+ ... ry = new-object System.Collections.Generic.Dictionary[[string],[int]]
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.NewObjectCommand

> $dictionary = new-object System.Collections.Generic.Dictionary[string,int]
New-Object : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ComObject'. Specified method is not supported.
At line:1 char:25
+ ... ionary = new-object System.Collections.Generic.Dictionary[string,int]
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.NewObjectCommand

我知道我可以在 PowerShell 下使用哈希表,但我想知道如何通过上述声明创建字典。

我错过了什么?

谢谢

【问题讨论】:

  • 转义, 逗号 使用反引号作为new-object System.Collections.Generic.Dictionary[[string]`,[int]],或使用引号作为new-object "System.Collections.Generic.Dictionary[[string],[int]]"
  • @JosefZ,谢谢。有用。请添加您的评论作为答案。

标签: powershell


【解决方案1】:

使用的类型名称System.Collections.Generic.Dictionary[[string],[int]] 包含一个逗号。 Creating and initializing an array:

要创建和初始化一个数组,请将多个值分配给一个 多变的。存储在数组中的值用分隔 逗号

因此,您需要转义逗号(阅读about_Escape_Charactersabout_Quoting_Rules 帮助主题)。还有更多选择:

在 Windows PowerShell 中,转义字符是 反引号 (`), 也称为重音(ASCII 96)。

$dictionary = new-object System.Collections.Generic.Dictionary[[string]`,[int]]

引号用于指定文字字符串。你可以附上 单引号 (') 或双引号 中的字符串 (")。

$dictionary = new-object "System.Collections.Generic.Dictionary[[string],[int]]"

$dictionary = new-object 'System.Collections.Generic.Dictionary[[string],[int]]'

【讨论】:

    【解决方案2】:

    问题在于 是如何解释你的论点的。

    当您在字符串中包含逗号时,它现在正在尝试绑定

    'System.Collections.Generic.Dictionary[[string]', '[int]]'
    

    -TypeName 类型的参数<string[]> 或错误消息中的<System.Object[]>。这可以通过正确引用您的参数来解决,使其与<string> 的预期参数绑定相匹配:

    New-Object -TypeName 'System.Collections.Generic.Dictionary[[string], [int]]'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多