PowerShell generic collections

人盡茶涼 提交于 2019-11-27 06:44:39
tomasr

Dictionary<K,V> is not defined in the same assembly as SortedDictionary<K,V>. 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]]"
ShanePowser

In PowerShell 2.0 the new way to create a Dictionary is:

$object = New-Object 'system.collections.generic.dictionary[string,int]'

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!