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"
}
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With