PowerShell Try/Catch and Retry

前端 未结 4 1997
故里飘歌
故里飘歌 2020-12-31 07:22

I have a fairly large powershell scripts with many (20+) functions which perform various actions.

Right now all of the code doesn\'t really have any error handling

4条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 07:41

    Solution with passing a delegate into a function instead of script block:

    function Retry([Action]$action)
    {
        $attempts=3    
        $sleepInSeconds=5
        do
        {
            try
            {
                $action.Invoke();
                break;
            }
            catch [Exception]
            {
                Write-Host $_.Exception.Message
            }            
            $attempts--
            if ($attempts -gt 0) { sleep $sleepInSeconds }
        } while ($attempts -gt 0)    
    }
    
    function MyFunction($inputArg)
    {
        Throw $inputArg
    }
    
    #Example of a call:
    Retry({MyFunction "Oh no! It happend again!"})
    

提交回复
热议问题