views:

2682

answers:

3

I have been pushing into the .Net framework in powershell and I have hit something that I don't understand. This works fine:

13# $foo = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
14# $foo.Add("FOO", "BAR")
15# $foo

Key                                                         Value
---                                                         -----
FOO                                                         BAR

This however does not:

16# $bar = New-Object "System.Collections.Generic.SortedDictionary``2[System.String,System.String]"
New-Object : Cannot find type [System.Collections.Generic.SortedDictionary`2[System.String,System.String]]: make sure t
he assembly containing this type is loaded.
At line:1 char:18
+ $bar = New-Object <<<< "System.Collections.Generic.SortedDictionary``2[System.String,System.String]"

THey are both in the same assembly, so what am I missing?

+4  A: 

There are some issues with Generics in PowerShell. Lee Holmes, a dev on the PowerShell team posted this script to create Generics.

I don't have time to test right now, but I'll try it out this evening.

Steven Murawski
+7  A: 

Dictionary is not defined in the same assembly as SortedDictionary. One is in mscorlib and the other in system.dll.

Therein lies the problem. The current behavior in powershell is that when resolving the generic parameters specified, if the types are not fully qualified type names, it sort of assumes that they are in the same assembly as the generic type you're trying to instantiate.

In this case, it means it's looking for System.String in System.dll, and not in mscorlib, so it fails.

The solution is to specify the fully qualified assembly name for the generic parameter types. It's extremely ugly, but works:

$bar = new-object "System.Collections.Generic.Dictionary``2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
tomasr
+6  A: 

In Powershell Version 2 the new way to create a Dictionary is $object = New-Object 'system.collections.generic.dictionary[string,int]'

ShanePowser