Search notes:

Implementing IEnumerator in PowerShell to use an object in a foreach statement

An object is required to implement the System.Collections.IEnumerator interface in order for the foreach statement to be able to iterate over the object. This example tries to demonstrate how an object can implement this interface.
The following example tries to demonstrate how an object can implement this interface.
class tq84Enumerator: System.Collections.IEnumerator {

   [int] $val

   tq84Enumerator() {
       $this.Reset();
   }

   [object] get_Current() {
      return $this.val
   }

   [bool] MoveNext() {
      $this.val++

      if ($this.val -gt 13) {
         return $false
      }
      return $true
   }

   [void] Reset() {
       $this.val = 7;
   }
}

$e = [tq84Enumerator]::new()
foreach ($f in $e) {
  $f
}
Github repository about-powershell, path: /language/statement/foreach/IEnumerator.ps1

Index