0

I have created a custom class in PowerShell which I would like to be able to access via the foreach command.

In PHP, I can do this by using implements iterator in my class declaration and implementing some variables and functions. Is there something similar in PowerShell? How do I let my PowerShell class be accessed by foreach?

Note: I'm using PowerShell Core

2
  • 1
    Can you show a example of what you are wanting to happen? maybe there is a better way then what you are thinking of Commented Oct 30, 2018 at 0:22
  • You need to implement IEnumerable interface. Commented Oct 30, 2018 at 4:47

1 Answer 1

1

You can extend some IEnumerable implementation like this:

class Test : System.Collections.Generic.List[PSObject]
{
    Test($items)
    {
        $items -split ';' |% { $this.Add($_) }
    }
}

$test = New-Object Test('a;1;x;y;z;2;3;4')

foreach ($item in $test)
{
    Write-Host $item
}

The result:

a
1
x
y
z
2
3
4
Sign up to request clarification or add additional context in comments.

Comments

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.