Question:
I have a simple question:
Why the program below does not write the whole array $lines
? It is looping forever. I am really confused..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function Get-Current ($enumerator) { $line = $enumerator.Current return $line } $lines = @('a', 'b', 'c') $enumerator = $lines.GetEnumerator() $enumerator.Reset() while ($enumerator.MoveNext()) { $line = Get-Current $enumerator "$line" } |
Answer:
It seems as though the expression:
1 2 |
$enumerator |
unwinds the entire enumerator. For e.g.:
1 2 3 4 5 6 7 8 |
PS C:\> $lines = @('a', 'b', 'c') PS C:\> $enumerator = $lines.GetEnumerator() PS C:\> $enumerator.Reset() PS C:\> $enumerator a b c |
So, when you try to pass your expression to the function, it is rendered invalid. The only workaround I can think of is to pass it as a PSObject like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function Get-Current ($val) { $val.Value.Current } $lines = @('a', 'b', 'c') $enumerator = $lines.GetEnumerator() $enumerator.Reset() while ($enumerator.MoveNext()) { $line = Get-Current $(get-variable -name enumerator) $line } |