Skip to main content

Invoking Code Repeatedly

Sometimes you might want to run some command multiple times until it runs successfully. Here is a function that shows a way to do this:

#requires -Version 2
function Invoke-CodeRepeatedly

    $RepeatCount = 4,
    $SleepMilliseconds = 3000

  $c = 0
      $ErrorActionPreference = 'Stop'
      & $ScriptBlock
      $doagain = $false
      $doagain = $c -lt $RepeatCount 
      if ($doagain -eq $false) { break }
      Write-Verbose "Error $_ trying again..."
      Start-Sleep -Milliseconds $SleepMilliseconds
  } while ($doagain)

You submit a script block with your code to Invoke-CodeRepeatedly and use -RepeatCount to specify how often the code should be tried. It repeats 4 times by default. -SleepMilliseconds is used to define the pause between tries. It waits for 3 seconds by default.

You could test this function like this:

Invoke-CodeRepeatedly -ScriptBlock { New-Item $env:temptestfolder -ItemType Directory  } -Verbose

When you run it the first time, it succeeds and creates a new folder. When you run it later, it fails because the folder is already present. It will now try again three times (a total of 4 tries) and waits 3 seconds between each try. If you delete the folder from another PowerShell while the function runs, you will see the code succeed again.

Twitter This Tip! ReTweet this Tip!

Posted Feb 26 2016, 06:00 AM by ps1


I am the one