Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell/GetEnumerator

I have a simple question:

Why the program below does not write 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"     
}
like image 259
Marek Pavluch Avatar asked Jun 04 '10 08:06

Marek Pavluch


People also ask

What does GetEnumerator do in PowerShell?

GetEnumerator in PowerShell is used to iterate through the Hashtable or array to read data in the collection. GetEnumerator doesn't modify the collection data. Use foreach or foreach-object in PowerShell to iterate over the data read from the GetEnumerator.

How do I get key value pairs in PowerShell?

The key/value pairs might appear in a different order each time that you display them. Although you cannot sort a hash table, you can use the GetEnumerator method of hash tables to enumerate the keys and values, and then use the Sort-Object cmdlet to sort the enumerated values for display.

How do I iterate through a Hashtable in PowerShell?

In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.

How do I create a hash in PowerShell?

To create a hash table in PowerShell, you'll use an @ symbol followed by an opening curly brace and a closing curly brace as shown below. Here you can see my hash table is now three lines with a key/value pair in the middle. It can also be represented on one line as well.


1 Answers

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
}
like image 138
zdan Avatar answered Sep 18 '22 23:09

zdan