I frequently have to loop through sets of data (SQL results, lists of computers, etc.) in PowerShell, performing the same operation (e.g function X) on each time. I use foreach loops almost exclusively as they are simple, effective and easily understood by others who may need to follow my code.
I would like to make some of my code more robust, in the sense of retrying operations that fail (up to Y times). There's more than one way to achieve this, for example within the foreach loop, wrapping function X in a do{} while() loop. In this example, assume that function X only returns non-null results when it is "successful":
foreach($dataitem in $dataset){
$Result = $null
$Attempts = 0
do{
$Attempts++
$Result = <call function X on $dataitem>
} while(($Attempts -lt 3) -and (-not $Result))
}
I was wondering whether there was any way to flatten this logic a bit, i.e. a more advanced way of using foreach loops, so I can do away with the do{} while() loop.
I have encountered the opposite of what I want, namely using $foreach.MoveNext() to skip forwards in the loop, but haven't found anything that (dangerously?) would keep foreach processing the same item.
Essentially: Can a foreach loop be made to re-do an iteration?.