I ran into similar problems a while ago. Take a look at this code:
I create my own Enumerator that prints some information about when it is called. Same as your SqlDataReader , which (I think) implements IEnumerator .
PS> Add-Type -TypeDefinition @" using System; using System.Collections; public class MyEnumerator2 : IEnumerator { private int _count = 10; private Random r = new Random(); public MyEnumerator2(int count) { _count = count; } public bool MoveNext() { Console.WriteLine("Moving!"); _count--; return _count >= 0; } public void Reset() { throw new NotImplementedException(); } public object Current { get { Console.WriteLine("Current!"); return r.Next(); } } } "@
Then create an object of type and try to output it:
PS> $mye = New-Object MyEnumerator2 5 PS> $mye | % -begin { write-host 'starting' } -Process { write-host 'next is ' $_ } starting Moving! Current! next is 2081278528 Moving! Current! next is 2000135673 Moving! Current! next is 692162542 Moving! Current! next is 1531746038 Moving! Current! next is 1550381634 Moving!
Everything is as expected. But now
PS> function iteratemye($o) { $o | % -begin { write-host 'starting' } -Process { write-host 'next is ' $_ } } PS> $mye = New-Object MyEnumerator2 5 PS> iteratemye $mye Moving! Current! Moving! Current! Moving! Current! Moving! Current! Moving! Current! Moving! starting Moving!
If you pass this enumerator to a function, it will be read before it reaches the body . This is very bad.
So take a look at your code. If you use some feature like my iteratemye , this is the cause of your problems.
Update: it does not implement IEnumerator , but IEnumerable . I see that you are simply passing the object to some constructor, which is not the same problem as mine, but I believe that PowerShell will still try to get the enumerator and do some magic.
source share