vik santata
vik santata

Reputation: 3109

powershell: creating a generic hashset with syntax error?

I tried this in powershell 4.0:

[System.Assembly]::LoadWithPartialName("System.Collections.Generic")
$m = New-Object '[System.Collections.Generic::HashSet](String)'
$m.GetType()

But running gives error. Is my usage incorrect? I only have 2 lines of code!

Unable to find type [System.Assembly]. Make sure that the assembly that contains this type is loaded.
At D:\Untitled1.ps1:1 char:1
+ [System.Assembly]::LoadWithPartialName("System.Collections.Generic")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Assembly:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound

New-Object : Cannot find type [[System.Collections.Generic::HashSet]                (String)]: verify that the assembly containing this type is loaded.
At D:\Untitled1.ps1:2 char:6
+ $m = New-Object '[System.Collections.Generic::HashSet](String)'
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidType: (:) [New-Object],         PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

You cannot call a method on a null-valued expression.
At D:\Untitled1.ps1:3 char:1
+ $m.GetType()
+ ~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

Upvotes: 1

Views: 3164

Answers (1)

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

LoadWithPartialName() is in [System.Reflection.Assembly], not [System.Assembly]. Also, your New-Object syntax is slightly off.

[System.Reflection.Assembly]::LoadWithPartialName("System.Collections.Generic")
$m = New-Object 'System.Collections.Generic.HashSet[String]'
$m.GetType()

See also: http://www.leeholmes.com/blog/2006/08/18/creating-generic-types-in-powershell/

Upvotes: 3

Related Questions