You don't need to have the index. In fact, it's a bit meaningless for hashtables as they are not stored in a set order like arrays. You can simply do this:
foreach ($item in $items.GetEnumerator()) {
Write-Progress -Activity 'Foo' -PercentComplete ($i++ / $items.Count *100) -CurrentOperation $item.key
Start-Sleep 2
}
If you're likely to run the code multiple times in one session, zero the count before the foreach
with $i = 0
.
If you do want the items processed in the order you added them, then add the [Ordered]
attribute to your hashtable:
$items = [Ordered]@{'x' = 'a'; 'y' = 'b'; 'z' = 'c'}
This will allows you to index into the hashtable (e.g. $thirdItem = $items[2]
), but doesn't provide anything like the IndexOf()
method, so you'll need to stick with the counter variable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…