How to do a controlled foreach iteration

Hi All,

in the original thread which can be found here

the solution provided by Doug was to use a function and the below foreach.
at this point the foreach will do 3 attempts before stopping. How can I adapt that that the code stops after the First or the Second attempt was successful?

$users = import-csv c:\temp\csv\toRemove.csv
 
$users | foreach {
    foreach($attempt in 1..3)
    {
        Remove-AzureGroupMember -Users $_ -Errorlog “c:\temp\groupdeletionErrors.txt”
        Start-Sleep -Seconds 1
    }
}

thanks for your assistance in this matter

You could try checking if the command was successful with $lastexitcode and if so exit the loop with continue

$users = import-csv c:\temp\csv\toRemove.csv
 
$users | foreach {
    foreach($attempt in 1..3)
    {
        Remove-AzureADGroupMember -ObjectId $_.objectID -Errorlog “c:\temp\groupdeletionErrors.txt”
        if($lastexitcode -eq 0)
        {
            continue
        }
        Start-Sleep -Seconds 1
    }
}

Another possible approach would be to confirm the user was removed and if so exit the loop.

$users = import-csv c:\temp\csv\toRemove.csv
 
$users | foreach {
    foreach($attempt in 1..3)
    {
        Remove-AzureADGroupMember -ObjectId $_.objectID -Errorlog “c:\temp\groupdeletionErrors.txt”
        if(-not (Get-AzureADGroupMember -ObjectID $_.objectID -ErrorAction SilentlyContinue))
        {
            continue
        }
        Start-Sleep -Seconds 1
    }
}

Thanks Doug for your reaction
however we the 3 attempts are remaining unfortunately
I would like to escape somehow if any of the 3 attempts was succesfull?

Paul