question

DavidGray-3700 avatar image
0 Votes"
DavidGray-3700 asked DavidGray-3700 answered

List<T> in PowerShell?

Hi,
Looking to create a List<T> in PowerShell but struggling to find out how to add properties to it. This is what I have so far but
I get an error message on Add or AddRange.

 using namespace System.Collections.Generic
    
 class Errors 
 {
     [string] $Y 
     [string] $X 
 }
    
    
 Clear-Host
    
    
 $Errors = New-Object List[Errors]
 $Errors.Add(New-Object -TypeName Errors -ArgumentList "0", "1")
 $Errors.Add("1", "2")
 $Errors.AddRange("3", "4")
 $Errors



This C# example shows what I'm trying to achieve

80557-image.png


dotnet-csharpwindows-server-powershell
image.png (34.0 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

cooldadtx avatar image
0 Votes"
cooldadtx answered

In general you shouldn't need to use List<T> directly in PS. Unless you're doing interop with a .NET type that requires it then just stick with PS arrays.

[System.Collections.Generic.List[Errors]] $errors = @()

# Or
$errors = New-Object System.Collections.Generic.List[Errors]


To add you need an Errors object.

$item = New-Object -TypeName Errors
$item.X = 1
$item.Y = 2

$errors += $item

# Or...
$errors.Add($item)


Your first add won't work because the Errors type doesn't have a constructor that accepts 2 parameters. The second add doesn't work because the Add function requires an Errors.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DavidGray-3700 avatar image
0 Votes"
DavidGray-3700 answered cooldadtx commented

Hi @cooldadtx

Thanks for your response, I got it working as below.

 Clear-Host
    
 class Errors 
 {
     [int] $Y 
     [int] $X 
 }
    
 $errors = New-Object System.Collections.Generic.List[Errors]
    
    
 [Errors] $item1 = New-Object -TypeName Errors
 # [Errors] $item2 = New-Object Errors 
    
 $item1.X = 1
 $item1.Y = 2
 $errors.Add($item1)
 $errors.Add($item1)

Was wondering if there's a way to create and assign $item1 in the .Add arguments list?

Thanks


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes. Option 1 is to define a constructor in your PS class. Option 2 is to use a hashtable.

[Errors]@{ X = "10"; Y = "20" }
1 Vote 1 ·
DavidGray-3700 avatar image
0 Votes"
DavidGray-3700 answered

Thanks @cooldadtx for your help :-)

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.