Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

hashtable - PowerShell Write-Progress while iterating over a hash GetEnumerator()

If you are iterating over an array it is easy to provide feedback using Write-Progress , thus:

$items = @('a', 'b', 'c')
foreach ($item in $items) {
  Write-Progress -Activity 'Foo' -PercentComplete ($items.IndexOf($item) * 100 / $items.Count) -CurrentOperation $item
  Start-Sleep 2
}

Is there a similar trick that can be used when iterating over a hash?

$items = @{'x' = 'a'; 'y' = 'b'; 'z' = 'c'}
foreach ($item in $items.GetEnumerator()) {
  Write-Progress ...
  Start-Sleep 2
}

I can still access $items.count, but there doesn't seem to be a way to get the index of the item from an the enumerator.

I appreciate that I can quite simply declare $i=0 at the start and include $i++ in the loop but is there another way?

question from:https://stackoverflow.com/questions/65884495/powershell-write-progress-while-iterating-over-a-hash-getenumerator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...