Reputation: 329
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
Upvotes: 0
Views: 1022
Reputation: 819
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
Upvotes: 1