List<T> in PowerShell?

David Gray 176 Reputation points
2021-03-23T11:59:41.057+00:00

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

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,218 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,358 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 47,806 Reputation points
    2021-03-23T15:06:21.647+00:00

    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.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. David Gray 176 Reputation points
    2021-03-23T17:06:09.977+00:00

    Hi @Michael Taylor

    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


  2. David Gray 176 Reputation points
    2021-03-24T15:57:15.95+00:00

    Thanks @Michael Taylor for your help :-)

    0 comments No comments