I'm using the following solution from here [passing a delegate into a function]https://stackoverflow.com/a/47712807/21295698).
I want to modify the $inputarg text each time an error is caught in the catch block. When action.invoke() is called the variable sent to MyFunction might be modified if ther's an error, say. (add the value of attempts to the end of the string, for example). So the output might be something like :
Oh no! It happened again! 1
Oh no! It happened again! 2
Oh no! It happened again! 3
I tried the following code, but have clearly run out of talent at this point. How does one achieve an overload for 'Invoke'? Or should one even try?
function Retry([Action]$action, $varToChange)
{
$attempts=3
$sleepInSeconds=1
do
{
try
{
$action.Invoke($varToChange);
break;
}
catch [Exception]
{
Write-Host $_.Exception.Message
$varTochange = $varTochange + $attempts
}
$attempts--
if ($attempts -gt 0) { Start-Sleep $sleepInSeconds }
} while ($attempts -gt 0)
}
function MyFunction($inputArg)
{
Throw $inputArg
}
#Example of a call:
Retry({MyFunction "It ran this many times : "}) 'It ran this many times : '