Search code examples
powershell

Create new System.Collections.Generic.Dictionary object fails in PowerShell


PowerShell version: 5.x, 6

I'm trying to create a new object of System.Collections.Generic.Dictionary, but it fails.

I tried the following "versions":

> $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

I know that I can use a hashtable under PowerShell, but I want to know how to create a dictionary via the above declaration.

What am I missing?

Thx


Solution

  • Used type name System.Collections.Generic.Dictionary[[string],[int]] contains a comma. By Creating and initializing an array:

    To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma

    Hence, you need to escape the comma (read the about_Escape_Characters and about_Quoting_Rules help topics). There are more options:

    In Windows PowerShell, the escape character is the backtick (`), also called the grave accent (ASCII 96).

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

    Quotation marks are used to specify a literal string. You can enclose a string in single quotation marks (') or double quotation marks (").

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

    or

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