2010-07-23 10 views
11

Me gustaría utilizar un HashSet en un script de powershell. Creo que he descubierto la manera de crear instancias de objetos de colección genéricos haciendo:¿Puedo usar System.Core.dll/System.Collections.Generic.HashSet en powershell?

[type] $strType = "string" 
$listClass = [System.Collections.Generic.List``1] 
$listObject = $base.MakeGenericType(@($t)) 
$myList = New-Object $setObject 

Esto funciona bien para las listas y diccionarios, pero cuando intento crear un HashSet me sale:

Unable to find type [System.Collections.Generic.HashSet`1]: make sure that the assembly containing this type is loaded. 

Así Parece que ahora necesito cargar System.Core.dll pero parece que no puedo obtener PowerShell para cargar ese ensamblaje. Por ejemplo llamando [System.Reflection.Assembly] :: LoadWithPartialName ("System.Core") causa esta excepción:

"LoadWithPartialName" with "1" argument(s): "Could not load file or assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified." 

Cualquier punteros?

+0

que están en PowerShell v1 o v2? – x0n

+0

Estoy en Win2k8 R2 y get-host dice la versión 2.0 – nick

+2

Posible duplicado: vea la respuesta a http://stackoverflow.com/questions/184476/powershell-generic-collections – zdan

Respuesta

21

PowerShell 2.0 hace que esto sea más fácil para el 1) añadir el cmdlet Add-Type para cargar un montaje y 2) cambios a la sintaxis para hacer que especifica un nombre de tipo genérico cerrado ejemplo más sencillo:

PS> Add-Type -AssemblyName System.Core 
PS> $h = new-object 'System.Collections.Generic.HashSet[string]' 
PS> $h.Add('f') 
True 
+0

Funciona muy bien, gracias. – nick

+0

¿Puedo entonces especificar el tipo de parámetro en funciones haciendo '[Parámetro (Obligatorio = $ verdadero)] [hashset]'? –

+2

Sí, pero debe especificar el tipo de parámetro como '[Collections.Generic.HashSet [string]]' sustituya la cadena del tipo que necesita almacenar en el hashset. –

Cuestiones relacionadas