Search code examples
powershellpowershell-5.0

Powershell list of objects of a class type


I am trying to iterate through a list of objects of a class type. The class looks like this :

Class UrlTestModel
{
    [String]$Name
    [String]$Url
    [String]$TestInProd
}

So I would like to be able to create a list of objects that contain the three strings above, then iterate through the list and do stuff with the data. For some reason I cant see a way to do that. Seems simple enough. I am kinda new to powershell, and come from a C# background, so I might be thinking too C# and not enough powershell. :)


Solution

  • You can create a new instance this way:

    New-Object -TypeName "UrlTestModel" -Property @{
        Name = "string"
        Url = "string"
        TestInProd = "string"
    }
    

    Or define a constructor in your class:

    class UrlTestModel
    {
        [String]$Name
        [String]$Url
        [String]$TestInProd
    
        UrlTestModel([string]$name, [string]$url, [string]$testInProd) {
            $this.Name = $name
            $this.Url = $url
            $this.TestInProd = $testInProd
        }
    }
    

    And then create a new instance like this:

    [UrlTestModel]::new("string", "string", "string")
    

    You can read more about it in about_Classes.

    Lists are basically created by using the comma operator:

    $list = [UrlTestModel]::new("name1", "url1", "true"), [UrlTestModel]::new("name2", "url2", "false")
    
    # or
    
    $a = New-Object -TypeName UrlTestModel -Property @{Name = "string"; Url = "string"; TestInProd = "string" }
    $b = New-Object -TypeName UrlTestModel -Property @{Name = "string"; Url = "string"; TestInProd = "string" }
    $list = $a, $b
    
    

    Iterate over a list using the ForEach-Object cmdlet or the foreach statement:

    $list | ForEach-Object {
        # this is the current item:
        $_
    }
    
    # or 
    
    foreach ($item in $list) {
        # ... 
    }