0

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 : '
  • You are using c# like parameters instead of PS parameters. See : https://www.techtarget.com/searchwindowsserver/tip/Understanding-the-parameters-of-Windows-PowerShell-functions?force_isolation=true#:~:text=The%20PowerShell%20parameter%20is%20a,without%20changing%20the%20underlying%20code. – jdweng Feb 27 '23 at 09:46

1 Answers1

0

I think add $index variable and increment it in loop. The calling function (MyFunction) can add a number to the sentence you provide when call the Retry function

function Retry([Action]$action)
{
    $attempts=3
    $index = 1    
    $sleepInSeconds=1
    do
    {
        try
        {
            $action.Invoke();
            break;
        }
        catch [Exception]
        {
            Write-Host $_.Exception.Message
        }            
        $attempts--
        $index++
        if ($attempts -gt 0) { sleep $sleepInSeconds }
    } while ($attempts -gt 0)    
}

function MyFunction($inputArg)
{
    Throw $inputArg + $index
}

#Example of a call:
Retry({MyFunction "It ran this many times : "})

Output:

It ran this many times : 1
It ran this many times : 2
It ran this many times : 3