Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use System.Core.dll/System.Collections.Generic.HashSet in powershell?

I'd like to use a HashSet in a powershell script. I think I've figured out how to instantiate generic collection objects by doing:

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

This works fine for lists and dictionaries, but when I try to create a HashSet I get:

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

So it looks like now I need to load System.Core.dll but I can't seem to get powershell to load that assembly. For example calling [System.Reflection.Assembly]::LoadWithPartialName("System.Core") causes this exception:

"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."

Any pointers?

like image 847
nick Avatar asked Jul 23 '10 18:07

nick


1 Answers

PowerShell 2.0 makes this easier by 1) adding the Add-Type cmdlet for loading an assembly and 2) updates to the syntax to make specifying a closed generic type name simpler e.g.:

PS> Add-Type -AssemblyName System.Core
PS> $h = new-object 'System.Collections.Generic.HashSet[string]'
PS> $h.Add('f')
True
like image 164
Keith Hill Avatar answered Nov 16 '22 23:11

Keith Hill