3

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. :)

1
  • 1
    If you already have a list of objects it's as simple as $list |ForEach-Object { <# Do somthing with $_ #> } or foreach($item in $list){ <# do something with $item here #> } Commented Oct 26, 2020 at 16:35

1 Answer 1

3

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) {
    # ... 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It didnt work while using the New-Object, but when declaring the class with a constructor, works a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.