PowerShell/GetEnumerator
I have a simple question:
Why the program below does not write 开发者_StackOverflow社区the whole array $lines? It is looping forever. I am really confused..
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"     
}
It seems as though the expression:
$enumerator
unwinds the entire enumerator. For e.g.:
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:
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
}
Don't know why MoveNext never returns false. This works
$lines = @('a', 'b', 'c')
$enumerator = $lines.GetEnumerator()
while ($enumerator.MoveNext()) {
    $enumerator.Current
}
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论