I'm trying to get the enumerator while looping a hash table.
I do understand how it works in a foreach loop like the following:
$test = @{set01 = '0'; set02 = '1'}
foreach ($t in $test.GetEnumerator()) {
Write-Host 'key: '$t.Key
}
Which would output the individual key per loop:
key: set02
key: set01
I'd like to know if it is possible to do that in a C type loop such as:
$test = @{set01 = '0'; set02 = '1'}
for ($i = 0; $i -lt 1; $i++) {
Write-Host 'key: '$test.Keys[$i] # edited with Dandré's answer.
}
Which lists all the keys:
key: set02 set01
key:
Is that possible or does the .GetEnumerator() only work in a foreach situation?
edit: Reading mklement0's answer i see that it's not directly possible. I'll mark it as the answer for the detailed explanation.
One workaround i figured out to extract the key for the loop position is partially linked to Dandré's answer combined with mklement0's explanation.
If the keys are collected into an array prior to running the loop they can be looked up while running the for loop.
$test = @{set01 = '0'; set02 = '1'}
$keys = @($test.Keys)
for ($i = 0; $i -lt $test.Count; $i++) {
Write-Host 'key:'$keys[$i]
}
This will result as expected:
key: set02
key: set01
depending on the array the keys need to be reversed first [array]::Reverse($keys).
The $keys variable can also be used within the loop to call specific keys as in: $test[$keys[$i]]. It's a bit of a hack but opens some interesting possibilities.