Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Constructor with Array Argument from Powershell

I'm a beginner in powershell and know C# moderately well. Recently I was writing this powershell script and wanted to create a Hashset. So I wrote($azAz is an array)

[System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collections.Generic.HashSet[string]($azAZ)

and pressed run. I got this message:

New-Object : Cannot find an overload for "HashSet`1" and the argument count: "52".
At filename.ps1:10 char:55
+ [System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collecti ...
+                                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId :         ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Then, I googled constructors in powershell with array parameters and changed the code to:

[System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collections.Generic.HashSet[string](,$azAZ)

Somehow, I now get this message:

New-Object : Cannot find an overload for "HashSet`1" and the argument count: "1".
At C:\Users\youngvoid\Desktop\test5.ps1:10 char:55
+ [System.Collections.Generic.HashSet[string]]$allset = New-Object System.Collecti ...
+                                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Cannot find an overload for HashSet and the argument count 1? Are you kidding me? Thanks.

like image 890
resgh Avatar asked Feb 03 '12 14:02

resgh


2 Answers

This should work:

[System.Collections.Generic.HashSet[string]]$allset = $azAZ

UPDATE:

To use an array in the constructor the array must be strongly typed. Here is an example:

[string[]]$a = 'one', 'two', 'three'
$b = 'one', 'two', 'three'

# This works
$hashA = New-Object System.Collections.Generic.HashSet[string] (,$a)
$hashA
# This also works
$hashB = New-Object System.Collections.Generic.HashSet[string] (,[string[]]$b)
$hashB
# This doesn't work
$hashB = New-Object System.Collections.Generic.HashSet[string] (,$b)
$hashB
like image 103
Rynant Avatar answered Oct 05 '22 20:10

Rynant


try like this:

C:\> $allset = New-Object System.Collections.Generic.HashSet[string]
C:\> $allset.add($azAZ)
True
like image 39
CB. Avatar answered Oct 05 '22 19:10

CB.